【发布时间】:2015-12-10 01:35:49
【问题描述】:
我正在尝试从字符串列表中索引字符串中的字符。
如果 stringV 是一个向量,这可行:
vector<string> stringV;
for (int i = 0; i < stringL.size(); i++) {
if(stringV[i][0] == 'a')
cout << stringV[i] << endl;
}
但如果 stringL 是一个列表,它就不起作用:
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>
我使用列表而不是向量的原因是我可以更有效地插入中间元素。关于如何从列表中的字符串索引字符有什么建议吗?
【问题讨论】:
-
stringV是如何定义的? (用答案编辑您的问题。) -
stringV 是一个向量(编辑了我的问题)
-
在你的第一个例子中,
stringV与stringL有什么关系?您正在使用stringL索引来访问stringV元素。还是您的意思是使用stringV.size()而不是stringL.size()? -
尝试使用括号:
if ((*it)[0] == '1'). -
@Thomas Matthews 这也有效,谢谢!