Open In App

GFacts | Why vector.size()-1 gives garbage value?

Last Updated : 24 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Vectors are the same as dynamic arrays with the ability to resize themselves automatically when an element is inserted or deleted, with their storage being handled automatically by the container.

Does vector.size() return the count of elements in the Vector?

The answer to the above question is yes it returns the count of elements in the vector.

Code to predict the output:

C++




// C++ code:
#include <bits/stdc++.h>
using namespace std;
 
// Drivers code
int main()
{
    vector<int> v;
    cout << v.size() - 1 << '\n';
    return 0;
}


Java




import java.util.ArrayList;
import java.util.List;
 
public class Main {
    public static void main(String[] args)
    {
        // Create a list of integers
        List<Integer> v = new ArrayList<>();
 
        // Print the size of the list minus 1
        System.out.println(v.size() - 1);
    }
}


Python




# Define the main function
def main():
    # Create a list of integers
    v = []
 
    # Print the size of the list minus 1
    print(len(v) - 1)
 
 
# Check if this script is being run directly
if __name__ == "__main__":
    # Call the main function
    main()


C#




using System;
using System.Collections.Generic;
 
class Program
{
    static void Main()
    {
        // Create a list of integers
        List<int> v = new List<int>();
 
        // Print the size of the list minus 1
        Console.WriteLine(v.Count - 1);
    }
}


Javascript




// Create an array of integers
let v = [];
 
// Print the size of the array minus 1
console.log(v.length - 1);


Expected Output:

-1

Actual Output:

18446744073709551615

You might expect the output to be −1. But the result is actually 18446744073709551615! Why?

What does the vector.size() actually return:

The following will give you 18446744073709551615. This is because vector.size() returns a size_t type value, which is an alias for unsigned long int. Unsigned values can not hold negative numbers so they underflowed to large numbers.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads