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

Supposedly we have the below: Example program#include <iostream>#include <string>#inc

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();
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742379337a4432818.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信