最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

C++ : if iterator is an object, why can't it be initialized to a reference iterator? - Stack Overflow

programmeradmin0浏览0评论

Supposedly we have the below:

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
  vector <int> v {1,2,3};
  vector <int>::iterator v_i1 = v.begin();
  vector <int>::iterator &v_i2 = v.begin(); // error out - initial value of reference to non-const must be an lvalue
}

Understanding:

  1. v.begin() will return an iterator - which is actually an object
  2. v_i1 a variable is initialized with the iterator return from begin(). No issue
  3. If v.begin() returns an iterator (object here??), why can't it be assigned to reference v_i2? Is it because v.begin() return a rvalue?

Thanks for helping me to understand better.

Supposedly we have the below:

// Example program
#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
  vector <int> v {1,2,3};
  vector <int>::iterator v_i1 = v.begin();
  vector <int>::iterator &v_i2 = v.begin(); // error out - initial value of reference to non-const must be an lvalue
}

Understanding:

  1. v.begin() will return an iterator - which is actually an object
  2. v_i1 a variable is initialized with the iterator return from begin(). No issue
  3. If v.begin() returns an iterator (object here??), why can't it be assigned to reference v_i2? Is it because v.begin() return a rvalue?

Thanks for helping me to understand better.

Share Improve this question edited Nov 21, 2024 at 4:10 yapkm01 asked Nov 20, 2024 at 5:33 yapkm01yapkm01 3,7819 gold badges40 silver badges67 bronze badges 3
  • v.begin() returns prvalue, so you should use vector <int>::iterator&&. – 康桓瑋 Commented Nov 20, 2024 at 5:43
  • Same, to_string() returns an string object which is prvalue. – 康桓瑋 Commented Nov 20, 2024 at 5:54
  • Who told you that objects cannot be rvalues? – digito_evo Commented Nov 20, 2024 at 7:57
Add a comment  | 

1 Answer 1

Reset to default 2

Non const reference can't bind to rvalue returnrd by std::vector::begin(). Make the reference to const.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
  vector <int> v {1,2,3};
  vector <int>::iterator v_i1 = v.begin();
  const vector <int>::iterator &v_i2 = v.begin();
}

Or, as commented, make it rvalue reference. The both prolong the temporary object' lifetime to the scope of the reference.

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main() {
  vector <int> v {1,2,3};
  vector <int>::iterator v_i1 = v.begin();
  const vector <int>::iterator &v_i2 = v.begin();
  vector <int>::iterator &&v_i3 = v.begin();
}
发布评论

评论列表(0)

  1. 暂无评论