본문 바로가기
C++

[C++/STL] How to find the size, length of a vector

by Warehaus 2024. 4. 21.

 

Photo by James Harrison on Unsplash

 

 

In C++, there are several ways to calculate the size of a vector, which indicates how many items it contains.

 

Although there isn’t a single definitive method, you can choose from the following summarized approaches. Keep in mind that there isn’t necessarily a right or wrong answer; consider these as reference points.

 

 

 

1. std::vector::size: This directly returns the size of the vector.

For example:

std::vector<int> v_ints;
cout << "size of vector: " << v_ints.size() << endl;
v_ints.push_back(1);
cout << "size of vector: " << v_ints.size() << endl;

 

 

 

2. Loop: This is a very primitive method. It’s separately organized because there might be cases where you don’t use the size member function.

 

For example:

std::vector<int> v_ints;
int count = 0;
for (auto& i : v_ints) {
    count++;
}
cout << "size of vector: " << to_string(count) << endl;

 

 

반응형

 

Knowing these methods should be enough to calculate the size of a vector without any issues.

 

The post also mentions that it’s possible to implement a method to count only items that meet specific conditions, and this topic will be covered in another post.

 

 

 

Thanks.