Reputation: 779
I'm used to languages where .Length
or whatever it may be returns an int
but I'm taking a C++ class so I gotta know how to do this. I asked my professor to explain but she didn't want to because the rest of the class is learning about arrays.
First of all, I don't think I fully understand what it is that .size
returns. How do I cast whatever .size
is to an int
? If it's not efficient to do this, how do I loop over the elements of a vector?
Upvotes: 1
Views: 2052
Reputation: 3911
Class std::vector
has a member function size()
which returns the number of elements pushed in. So use it to get the size as an integer value:
std::vector<int> vecInt;
vecInt.push_back(1);
vecInt.push_back(2);
vecInt.push_back(3);
vecInt.push_back(4);
vecInt.push_back(5);
std::cout << vecInt.size(); // 5
Upvotes: 0
Reputation: 29013
std::vector::size
is a member function. You have to call it and it returns the size of the vector. You want to use .size()
not .size
. Using .size
refers to the function (for example if you want to take it's address) where as .size()
calls the function.
There are several ways of looping over a vector. The most generic method is the range-based for loop. It works with all standard containers, any user-defined container that provides a proper begin
and end
method, as well as arrays. For example :
for(const auto & element: my_vect) {
proc(element);
}
Will call the function proc
with every element in the vector my_vect
.
Upvotes: 3