Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vector<string>::iterator - how to find position of an element

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

like image 620
user2754070 Avatar asked Oct 18 '13 04:10

user2754070


People also ask

How do you find the position of an element in a vector?

find(): Used to find the position of element in the vector. Subtract from the iterator returned from the find function, the base iterator of the vector . Finally return the index returned by the subtraction.

How do you get an iterator of a particular element in an vector?

Using std::next function In C++11 and above, the recommended approach is to use std::next, which advances the specified iterator by the specific number of elements. That's all about getting an iterator to a specific position in a vector in C++.

How do you find an element in vector STL?

How do we find an element using STL? Approach 1: Return index of the element using std::find() Use std::find_if() with std::distance() Use std::count()


3 Answers

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();
like image 81
juanchopanza Avatar answered Sep 28 '22 17:09

juanchopanza


Use following :

if(it != vec.end())
   std::cout<< "Found At :" <<  (it-vec.begin())  ;
like image 35
P0W Avatar answered Sep 28 '22 18:09

P0W


#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;
like image 36
Pingakshya Goswami Avatar answered Sep 28 '22 17:09

Pingakshya Goswami