Vladislav Vladislav - 1 year ago 92
C++ Question

Getting position of char in vector (C++)

I am trying to check if char exists in vector of chars, and if so, to get it`s number. I have done the first part (check if char exists):

char letter(a);
string word;
vector<char>vWord(word.begin(), word.end());
if(find(vWord.begin(), vWord.end(), letter) != vWord.end()){}

But I have no idea how to get the position. Any help is appreciated.

Answer Source

Save the iterator and do some math on it:

vector<char>::iterator itr = find(vWord.begin(), vWord.end(), letter);
if(itr != vWord.end())
   int index = itr - vWord.begin();

However do note that std::string already has a find method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download