gpt4 book ai didi

c++ - 使用迭代器访问成员字符串时出错::空

转载 作者:行者123 更新时间:2023-11-28 06:45:41 24 4
gpt4 key购买 nike

我一直在阅读文本 Material 来磨练我的 C++ 技能,但在我的迭代器字符串实验中遇到了问题。我想要做的是获取一个字符串,遍历字符串中的每个元素,并输出字符串中的每个元素。但是,由于我正在学习如何使用箭头运算符,编译器告诉我无法访问成员 string::empty。变量 aIter 的类型不是 string::iterator 吗?

#include <iostream>
#include <string>

using namespace std;

int main()
{
string sString("some string!");
for(auto aIter = sString.cbegin();
aIter != sString.cend() && !aIter->empty();
aIter++)
cout << *aIter << endl;

cout << endl;

return 0;
}

Error:
request for member 'empty' in '* aIter.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator-><const char*, std::basic_string<char> >()', which is of non-class type 'const char'|

最佳答案

您正在迭代字符串的字符。字符没有成员函数,也没有“空”的概念。

您可能只想删除 !aIter->empty() 测试,以迭代直到到达字符串末尾。即使字符串为空,这也会起作用:cbegin() 迭代器将等于 cend() 迭代器,因此循环将立即结束。

如果你想检查字符串是否为空(你不需要在这里做),那就是 sString.empty()

关于c++ - 使用迭代器访问成员字符串时出错::空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25036663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com