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.
'C++' 카테고리의 다른 글
Python과 Go: 미래의 프로그래밍 언어는 어떤 것이 더 유망할까? (2) | 2024.04.21 |
---|---|
C++ extern 개념, 사용방법 정리 (0) | 2024.04.21 |
[C++] nullptr과 NULL차이 - nullptr 조건문 사용시 주의사항 (0) | 2024.03.19 |
C와 C++이 백악관에서 더 이상 사용하지 않게 된 이유 (0) | 2024.03.17 |
[C++] const 의 개념 그리고 포인터 에서의 const (0) | 2022.03.27 |