Vladislav Vladislav - 5 days ago 7
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

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.

Comments