Search code examples
c++stringvectoriterator

Accessing a char in a vector of strings by its iterator


Here's a part of my code:

std::vector<std::string> syntax_words;
//...
//Currently the above vector contains few strings
std::vector<std::string>::iterator sy_iterator = syntax_words.begin(); 

while (sy_iterator != syntax_words.end(){
    if (*sy_iterator[4] == 'X'){
//...

Basically I want to access the fifth char in the current string. Unfortunately the above code is throwing an error during compilation:

error: no match for ‘operator*’ (operand type is ‘std::basic_string<char>’)
      if (*sy_iterator[4] == 'X'){

I've also tried this:

if (sy_iterator[4] == 'X'){

But it's also throwing an error:

error: no match for ‘operator==’ (operand types are ‘std::basic_string<char>’ and ‘char’)
      if (sy_iterator[sit] == 'X'){

What should I do to make it work?


Solution

  • Try the following

    while ( sy_iterator != syntax_words.end() )
    {
        if ( sy_iterator->size() > 4 && ( *sy_iterator )[4] == 'X')
        {
            //...
    

    The problem with your original code snippet is related to priorities of operators. Postfix operator [] has higher priority than unary operator *. Thus this expression

    *sy_iterator[4]
    

    is equivalent to

    *( sy_iterator[4] )
    

    Expression sy_iterator[4] will yield a string pointed to by iterator sy_iterator + 4 to which you are trying to apply operator *. But class string has no operator *. So the compiler issues an error.

    As for this statement

    if (sy_iterator[4] == 'X'){
    

    then here you are trying to compare iterator sy_iterator + 4 with character literal 'X'. Because there is no such an implicit conversion from one operand of the comparison to another operand then the compiler also issues an error.

    Take into account that class std;:vector has rnadom access iterators so for example expression

    syntax_words.begin() + 4
    

    will yield fourth iterator relative to the itertor returned by member function begin().