gpt4 book ai didi

c++ - 无法将 const_iterator 绑定(bind)到 const_iterator

转载 作者:行者123 更新时间:2023-12-03 07:22:27 25 4
gpt4 key购买 nike

#include <iostream>
#include <vector>

using namespace std;

void print(vector<int>::const_iterator &beg, vector<int>::const_iterator &end);

int main()
{
vector<int> ivec = {1, 2, 3, 4, 5};
print(ivec.cbegin(), ivec.cend());

return 0;
}

void print(vector<int>::const_iterator &beg, vector<int>::const_iterator &end)
{
if (beg == end)
{
cout << "over" << endl;
return;
}
cout << *beg << endl;
print(++beg, end);
}
ubuntu 20,g++ 9.0
rec_print_vect.cpp: In function ‘int main()’:
rec_print_vect.cpp:11:19: error: cannot bind non-const lvalue reference of type ‘std::vector<int>::const_iterator&’ {aka ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >&’} to an rvalue of type ‘std::vector<int>::const_iterator’ {aka ‘__gnu_cxx::__normal_iterator<const int*, std::vector<int> >’}
11 | print(ivec.cbegin(), ivec.cend());
| ~~~~~~~~~~~^~
rec_print_vect.cpp:6:41: note: initializing argument 1 of ‘void print(std::vector<int>::const_iterator&, std::vector<int>::const_iterator&)’
6 | void print(vector<int>::const_iterator &beg, vector<int>::const_iterator &end);

const int &i = 10是法律,对吧?为什么 const_iterator不能?我很困惑。这个程序只想递归打印一个 vector 。我想为迭代器使用引用。因为我不需要修改 vector 中的元素,所以我将 const_iterator 与 cbegin() 和 cend() memeber 函数一起使用。我认为将 const var 引用绑定(bind)到 const var 或文字值是正确的。但是我的代码无法通过编译阶段。如果我在函数形式参数中使用 const_iterator 而不是 const_iterator&,我的代码可以运行良好。

最佳答案

干得好:

void print(vector<int>::const_iterator beg, vector<int>::const_iterator end);
问题是,您不能将临时(由 begin() 等人返回的迭代器)绑定(bind)到非常量引用。所以要么接受 vector<int>::const_iterator const&或按值获取这些迭代器(这还不错)。

关于c++ - 无法将 const_iterator 绑定(bind)到 const_iterator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64738424/

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