gpt4 book ai didi

c++ - cbegin函数的返回值

转载 作者:行者123 更新时间:2023-12-01 15:13:20 24 4
gpt4 key购买 nike

我有这样的代码

#include <iostream>
#include <string>

int main() {

std::string str{"My short string."};

for (auto& it = str.cbegin(); it != str.cend(); ++it)
std::cout << *it;

return 0;
}

我收到一个错误:“引用非常量的初始值必须是左值
"

我想使用 auto& it = str.cbegin() ,为什么我不能这样做?我想, cbegin 返回一个迭代器对象,我不想复制它,所以我使用 & 语法。

你能解释一下,cbegin 是如何工作的,它的返回值是什么?

最佳答案

std::string::cbegin() 按值返回迭代器,它返回的是一个右值,并且对非常量的左值引用不能绑定(bind)到右值。

I don't wanna copy it, so I use & syntax.



复制迭代器根本不重,所以只需
for (auto it = str.cbegin(); it != str.cend(); ++it)
std::cout << *it;

关于c++ - cbegin函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60990507/

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