11

I am using the following code to find a string in an std::vector of string type. But how to return the position of particular element?

Code:

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    vector<string> vec;
    vector<string>::iterator it;

    vec.push_back("H");
    vec.push_back("i");
    vec.push_back("g");
    vec.push_back("h");
    vec.push_back("l");
    vec.push_back("a");
    vec.push_back("n");
    vec.push_back("d");
    vec.push_back("e");
    vec.push_back("r");

    it=find(vec.begin(),vec.end(),"r");
    //it++;

    if(it!=vec.end()){
        cout<<"FOUND AT : "<<*it<<endl;
    }
    else{
        cout<<"NOT FOUND"<<endl;
    }
    return 0;
}

Output:

FOUND AT : r

Expected Output:

FOUND AT : 9

user2754070
  • 489
  • 1
  • 7
  • 16
  • Possible duplicate of [How to get position of a certain element in strings vector, to use it as an index in ints vector?](https://stackoverflow.com/questions/15099707/how-to-get-position-of-a-certain-element-in-strings-vector-to-use-it-as-an-inde) – hmofrad Sep 06 '18 at 02:08

4 Answers4

24

You can use std::distance for that:

auto pos = std::distance(vec.begin(), it);

For an std::vector::iterator, you can also use arithmetic:

auto pos = it - vec.begin();
juanchopanza
  • 210,243
  • 27
  • 363
  • 452
  • Thanks! just out of my curiosity what if my vector contains `1000 elements` and using `find` will it be faster or I need to use some sort of `pointer to array`? – user2754070 Oct 18 '13 at 05:05
  • @user2754070 you would have to measure it, but I doubt you'll be faster than `find` in an optimized build. – juanchopanza Oct 18 '13 at 05:09
3

Use following :

if(it != vec.end())
   std::cout<< "Found At :" <<  (it-vec.begin())  ;
P0W
  • 42,046
  • 8
  • 62
  • 107
3
#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {
    vector<string> vec;
    vector<string>::iterator it;

    vec.push_back("H");
    vec.push_back("i");
    vec.push_back("g");
    vec.push_back("h");
    vec.push_back("l");
    vec.push_back("a");
    vec.push_back("n");
    vec.push_back("d");
    vec.push_back("e");
    vec.push_back("r");

    it=find(vec.begin(),vec.end(),"a");
    //it++;
    int pos = distance(vec.begin(), it);

    if(it!=vec.end()){
        cout<<"FOUND  "<< *it<<"  at position: "<<pos<<endl;
    }
    else{
        cout<<"NOT FOUND"<<endl;
    }
    return 0;
0

Use this statement:

it = find(vec.begin(), vec.end(), "r") - vec.begin();
pacholik
  • 7,596
  • 8
  • 43
  • 50