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
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.
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 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()
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();
                        Use following :
if(it != vec.end())
   std::cout<< "Found At :" <<  (it-vec.begin())  ;
                        #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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With