Get the vector element index

Hello,

i'm trying to get a vector element index in a vector of string, but i get weird results. Could someone explain the best and the fastest method to use?

1
2
3
4
5
 for (long index=0; index<(long)words.size(); ++index) {
        if  (words.at(index)=="Hello") {
            cout << "Word at index: " << index << endl;
        }
    }
Last edited on
What do you mean by weird results? What output do you get and what output do you expect?
Thank you for the reply.

I expect that the word i'm looking for is at position 1,2,3....

but i get 234345235 or similar strange number
I don't think the problem is in the code you have posted. Could you post a real code example of a program that reproduces this problem?
vector of string
std::string's?

Have you tried using compare rather than '==' on line 2?
http://www.cplusplus.com/reference/string/string/compare/

(although your sample should work as is to be honest)
Last edited on
No, havent tried.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
I tried with this code and it works:

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

   it=find(words.begin(),words.end(),"Verbal Predicate");
    //it++;

    if(it != words.end())
   std::cout<< "Found At :" <<  (it-words.begin())  ;

return (it-words.begin());

}



Find my error:

i was using a wrong vector with similar name.

Shame on me.

The old code works well.
Topic archived. No new replies allowed.