Keeping a reference to a vector element valid after resizing

笑着哭i 提交于 2019-12-24 04:56:10

问题


If we make a reference to a vector element and then resize the vector, the reference is no longer valid, the same happens with an iterator:

std::vector<int> vec{0, 1, 2, 3, 4, 5};
int& ref = vec[0];
auto itr = vec.begin();

cout <<  ref << " " << *itr << endl;

vec[0] = 7;

cout <<  ref << " " << *itr << endl;

vec.resize(100);
vec[0] = 3;

cout <<  ref << " " << *itr << endl;

Prints out:

0 0
7 7
0 0 // We expected a 3 here

And I know that it would be more practical to just keep a reference to the vector itself and call vec[0], but just for the sake of questioning, is it possible to keep an object that will always be vec[0] even if the object is moved?

I've tried writing a small helper class to help with this, but I'm unsure if this is the best method or if it can even fail?

template<typename T>
struct HelperClass
{
    std::vector<T>& vec;
    size_t element;

    HelperClass(std::vector<T>& vec_, size_t element_) : vec(vec_) , element(element_) {}

    // Either define an implicit conversion from HelperClass to T
    // or a 'dereference' operator that returns vec[0]
    operator T&() { return vec.at(element); }
    T& operator*() { return vec.at(element); }
};

And use it by either the implicit conversion to T& or by the 'dereference' operator:

std::vector<int> vec{0, 1, 2, 3, 4, 5};
int& ref = vec[0];
auto itr = vec.begin();
HelperClass<int> hlp = HelperClass<int>(vec, 0); // HelperClass

cout <<  ref << " " << *itr << " " << hlp << " " << *hlp << endl;

vec[0] = 7;

cout <<  ref << " " << *itr << " " << hlp << " " << *hlp << endl;

vec.resize(100);
vec[0] = 3;

cout <<  ref << " " << *itr << " " << hlp << " " << *hlp << endl;

Which already prints what was excepted:

0 0 0 0 
7 7 7 7
0 0 3 3

So is there a better way to do this aside from having a helper class and can the helper class be unreliable in some cases?

I've also come across this thread in reddit, but it seems that they do not discuss the helper class there


回答1:


The one thing you could do is have a vector of pointers rather than a vector of instances. That of course has its own passel of issues but if you must have object references survive a vector resize that will do it.




回答2:


Any reallocation of the vector will invalidate any pointers, references and iterators.

In your example, your HelperClass is useless in sense that this:

cout <<  ref << " " << *itr << " " << hlp << " " << *hlp << endl;

is the same as:

cout <<  ref << " " << *itr << " " << vec[0] << " " << vec[0] << endl;

If a reallocation happens, just use the iterator interface .begin() .end() to access again the iterators.



来源:https://stackoverflow.com/questions/50867703/keeping-a-reference-to-a-vector-element-valid-after-resizing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!