how to find number of elements in vector c++ code example

Example 1: c++ vector size

#include <vector>

int main() {
  std::vector<int> myVector = { 666, 1337, 420 };
  
  size_t size = myVector.size(); // 3
  
  myVector.push_back(399); // Add 399 to the end of the vector
  
  size = myVector.size(); // 4
}

Example 2: count function c++

1 #include <iostream>
2 #include <array>
3 #include <algorithm>
4
5 using namespace std;
6
7 int main(){
8 array<int, 5> nums = {1, 2, 3, 100, 2};
9 //counting number of twos
10 int numOccurrences = count(nums.begin(), nums.end(), 2);
11 cout << 2 << " appeared " << numOccurrences << " times" << endl;
12 return 0;
13 }
14
15 /*
16 2 appeared 2 times
17 */

Example 3: find a number in vector c++

find (vec.begin(), vec.end(), ser);

Tags:

Cpp Example