while programming I found out that my code was giving runtime error when I was using condition i < vec.size() - 1
but was working fine for i + 1< vec.size()
.
here vec
was an empty std::vector
.
//giving error
vector<int> vec;
for (int i = 0; i < vec.size() - 1; i++)
{
//some code
}
//not giving error
vector<int> vec;
for (int i = 0; i + 1 < vec.size(); i++)
{
//some code
}
The size of a vector represents the number of components in the vector. The capacity of a vector represents the maximum number of elements the vector can hold.
If the vector container is empty what will size() and empty() returns? Size will return 0 and empty will return 1 because if there is no element in the vector the size of that vector will be 0 and empty will be true so it will return 1.
To get the size of a C++ Vector, you can use size() function on the vector. size() function returns the number of elements in the vector.
The vector length (or magnitude) is the length of its arrow and corresponds to the distance between initial point and terminal point. For determining the length of the arrow (and thus the magnitude of the vector), think of the following triangle.
1 If the given value of n is less than the size at present then extra elements are demolished. 2 If n is more than current size of container then upcoming elements are appended at the end of the vector.
This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity. The number of elements in the container. Member type size_type is an unsigned integral type. Constant. No changes.
Size of the vector container is increased. Size of the vector container is increased and new elements are initialized with specified value. Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.
If n is more than current size of container then upcoming elements are appended at the end of the vector. n – it is new container size, expressed in number of elements.
The method std::vector::size
returns a std::size_t
which is unsigned. So if it is empty, you will get 0 - 1
, but represented as an unsigned number, that will underflow and become 18446744073709551615
according to two's complement.
Sidenote. It's not a good idea to compare signed and unsigned numbers. In C++20 we will have a new function std::ssize
that returns a signed type. Then your example written as
for (std::ptrdiff_t i = 0; i < std::ssize(vec) - 1; ++i)
{
//some code
}
will be perfectly valid.
Note also how i
is declared to be an std::ptrdiff_t
(a signed integer type) to indicate array indexing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With