GFacts | Why vector.size()-1 gives garbage value?
Last Updated :
24 Feb, 2024
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++
#include <bits/stdc++.h>
using namespace std;
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)
{
List<Integer> v = new ArrayList<>();
System.out.println(v.size() - 1 );
}
}
|
Python
def main():
v = []
print ( len (v) - 1 )
if __name__ = = "__main__" :
main()
|
C#
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List< int > v = new List< int >();
Console.WriteLine(v.Count - 1);
}
}
|
Javascript
let v = [];
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.
Share your thoughts in the comments
Please Login to comment...