STL find in C++

Level 4209 keystrokes

Searches a vector for 30 with find and, because it is found, prints its index computed from the iterator: 2.

C++ code

1vector<int> nums = {10, 20, 30, 40, 50};
// find returns an iterator to the first 30, or end() if there is none
2auto it = find(nums.begin(), nums.end(), 30);
// Comparing with end() tells whether the value was found
3if (it != nums.end()) {
// Subtracting begin() gives the index: prints Found at index: 2
4 cout << "Found at index: " << (it - nums.begin()) << endl;
5} else {
// Runs only if the value is missing (not the case here)
6 cout << "Not found" << endl;
7}

Output

Found at index: 2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 11
  • (× 7
  • )× 7
  • ,× 6
  • ;× 4
  • .× 4
  • "× 4
  • {× 3
  • }× 3
  • =× 3

More C++ examples at level 4

← C++ typing practice