如何在C ++中存储和添加链接到引用向量?(How do I store and add links to a vector of references in C++?)

我有一种情况,我有一个Class1对象和一个Class2对象的向量。 我的目标是让Class1的对象包含对Class2向量中某些对象的引用。 Class1包含成员:

std::vector<Class2&> links; void addLink(Class2 &obj) { links.push_back(obj) }

然后我想迭代Class2的对象,对于满足某个条件的任何对象,我想添加如下链接:

for (std::vector<Class2&>::iterator i = vector2.begin(); i != vector2.end(); ++i) { if (condition_satisfied(*i)) { obj1.addLink(*i) } }

但是,这样做会给我C2528的编译时错误:指向引用的指针是非法的。 我在这做错了什么?

I have a situation in which I have an object of Class1 and a vector of objects of Class2. My goal is to have the object of Class1 contain references to certain objects in the vector of Class2. Class1 contains the members:

std::vector<Class2&> links; void addLink(Class2 &obj) { links.push_back(obj) }

I then want to iterate through the objects of Class2 and for any objects which meet a certain condition, I want to add a link like so:

for (std::vector<Class2&>::iterator i = vector2.begin(); i != vector2.end(); ++i) { if (condition_satisfied(*i)) { obj1.addLink(*i) } }

However, doing this gives me compile-time errors of C2528: pointer to reference is illegal. What am I doing wrong here?

最满意答案

std::vector<T>要求T在C ++ 98中是CopyAssignable ,在C ++ 11中是Eraseable ,但是普通的引用都不是。 换句话说,引用不能存储在std::vector 。

您可能希望使用普通指针。 或std::reference_wrapper<T> ,这是伪装的指针。

std::vector<T> requires T to be CopyAssignable in C++98, Eraseable in C++11, but a plain reference is neither. In other words, references cannot be stored in std::vector.

You may like to use plain pointers instead. Or std::reference_wrapper<T>, which is a pointer in disguise.

更多推荐