[英]cannot bind const_iterator to const_iterator
#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
是leagl,對嗎? 為什么const_iterator
不能? 我很困惑。 這個程序只是想遞歸打印一個向量。 我想對迭代器使用引用。 因為我不需要修改向量中的元素,所以我使用了帶有 cbegin() 和 cend() memeber 函數的 const_iterator。 我認為將 const var 引用綁定到 const var 或文字值是正確的。 但是我的代碼無法通過編譯階段。 如果我在函數 fomal args 中使用 const_iterator 而不是 const_iterator&,我的代碼可以運行良好。
干得好:
void print(vector<int>::const_iterator beg, vector<int>::const_iterator end);
問題是,您不能將臨時值(由 begin() 等人返回的迭代器)綁定到非常量引用。 所以要么接受vector<int>::const_iterator const&
要么接受這些迭代器的值(這還不錯)。
函數參數
void print(vector<int>::const_iterator &beg, vector<int>::const_iterator &end);
是非常量引用。 雖然此調用中的參數
print(ivec.cbegin(), ivec.cend());
是由功能部件返回的臨時對象cbegin
和cend
。 您不能將非常量左值引用與臨時對象綁定。
像這樣聲明函數
void print(vector<int>::const_iterator beg, vector<int>::const_iterator end);
請注意,由於此語句,該函數在為空向量調用時可能會調用未定義的行為
if (beg + 1 == end)
該函數可以定義得更簡單。
void print(vector<int>::const_iterator beg, vector<int>::const_iterator end)
{
if ( beg != end )
{
std::cout << *beg << '\n';
print( ++beg, end );
}
}
或者,可以定義函數,如下面的演示程序所示。
#include <iostream>
#include <vector>
#include <iterator>
std::ostream & print( std::vector<int>::const_iterator beg,
std::vector<int>::const_iterator end,
std::ostream &os = std::cout )
{
return beg != end ? os << *beg << '\n', print( ++beg, end ) : os;
}
int main()
{
std::vector<int> ivec = {1, 2, 3, 4, 5};
print( std::begin( ivec ), std::end( ivec ) ) << std::endl;
return 0;
}
它的輸出是
1
2
3
4
5
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.