Home > other >  Find index of vector element using search_n function
Find index of vector element using search_n function

Time:04-05

I need to find index of vector element using a function from algorithm library.

EXAMPLE:

{1,2,3,4,5,6,7,8,9,10}

Element 5 found at 5 position.

#include <algorithm>
#include <iostream>
#include <vector>
bool comp(int a, int b) { return a < b; }
int main() {
  int n = 10;
  std::vector<int> a{10, 8, 5, 4, 1, 2, 3, 6, 7, 9};
  sort(a.begin(), a.begin()   n, comp);
  int number = 5;
  std::vector<int>::iterator it;
  it = std::search_n(a.begin(), a.begin()   n, number);
  if (it != a.end())
    std::cout << "found at position " << (it - a.begin()) << '\n';
  else
    std::cout << "match not found\n";
  return 0;
}

I get error (in the 11th line):

no matching function for call to ‘search_n(std::vector::iterator, __gnu_cxx::__normal_iterator >, int&)’

Could you explain me what is the problem here?

CodePudding user response:

The std::search_n function looks for a sequence of a specified number of occurrences of a particular value in a range; that number is the third argument (count on this cppreference page).

So, if you insist on using std::search_n for this, you will need to add an extra argument (count, which will be 1) in your call:

it = std::search_n(a.begin(), a.begin()   n, 1, number);

However, using search_n is something of an overkill when looking for a single value; better to use the simpler (and faster) std::find function. Also, in place of a.begin() n, you can use the easier and clearer a.end().

it = std::find(a.begin(), a.end(), number);

Also note that indexes and iterator positions in C start at zero, so, with the above fix(es) applied to your code, the answer will be "found at position 4"; if you want a 1-based position, then add 1 to the position.

  • Related