简体   繁体   中英

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?

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().

you can simply go like this:
DEMO

#include <iostream>
#include <vector>

using namespace std;

int main() {
    // your code goes here
        std::vector<std::string> syntax_words;
        syntax_words.push_back("urs X is here");
    for (string str : syntax_words){
      if(str.size() > 5 && str.at(4) == 'X')
        cout << "found" << endl;
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM