如何对列表c++中的字符串中的字符进行索引

How to index character in string from a list c++

本文关键字:字符 索引 字符串 列表 c++      更新时间:2023-10-16

我正试图从字符串列表中为字符串中的一个字符编制索引。

如果stringV是一个矢量,那么它就起作用:

vector<string> stringV;
for (int i = 0; i < stringL.size(); i++) {
    if(stringV[i][0] == 'a')
        cout << stringV[i] << endl;
}

但如果字符串L是一个列表,它就不起作用:

list<string> stringL;
for (list<string>::iterator it = stringL.begin(); it != stringL.end(); it++) {
    if (*it[0] == 'a')
        cout << *it << endl;
}

这也不起作用:

for (list<string>::iterator it = stringL.begin(); it != stringL.end(); it++) {
    if (*it.at(0) == 'a')
        cout << *it << endl;
}

这些是我的头文件:

include <string>
include <list>
include <vector>

我使用列表而不是向量的原因是为了更有效地插入中间元素。关于如何从列表中的字符串中索引字符,有什么建议吗?

使用(*it).at(0)it->at(0)代替*it.at(0)

表达式*it.at(0)解析为*(it.at(0)),这是没有意义的:char不能被取消引用。