【问题标题】:How to index character in string from a list c++如何从列表c ++中索引字符串中的字符
【发布时间】: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 是一个向量(编辑了我的问题)
  • 在你的第一个例子中,stringVstringL 有什么关系?您正在使用 stringL 索引来访问 stringV 元素。还是您的意思是使用stringV.size() 而不是stringL.size()
  • 尝试使用括号:if ((*it)[0] == '1').
  • @Thomas Matthews 这也有效,谢谢!

标签: c++ string list char


【解决方案1】:

使用(*it).at(0)it-&gt;at(0) 代替*it.at(0)

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

【讨论】:

    猜你喜欢
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-14
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 2020-02-17
    相关资源
    最近更新 更多