C++ Can';t在包含引用的类的向量中插入元素

C++ Can';t在包含引用的类的向量中插入元素,c++,vector,stl,C++,Vector,Stl,我有一个类,它引用了另一个结构 struct DNA { ... }; class Cohort { private: DNA& genetics; ... public: Cohort(DNA& g) : genetics(g) {} ... }; 然后我有一个向量队列s std::vector<Cohort> cohorts; 我犯了一个错误 error: object of ty

我有一个类,它引用了另一个结构

struct DNA { ... };
class Cohort {
    private:
        DNA& genetics;
        ...
    public:
        Cohort(DNA& g) : genetics(g) {}
        ...
};
然后我有一个向量
队列
s

std::vector<Cohort> cohorts;
我犯了一个错误

error: object of type 'Thor_Lucas_Development::Cohort' cannot be assigned because its copy assignment
      operator is implicitly deleted
我假设当项目插入到向量中时,它会被复制。因为我在我的
队列
s类中有一个引用,它的复制赋值操作符被隐式删除

所以。。。发生什么事?我就是不能在处理
群组
类时使用向量?或者我必须
new
进入
队列
并在向量中有指向它的指针吗


有点烦人。

您可以在适当的位置构建对象:

cohorts.emplace(cohorts.begin(), eggs, genetics); 
但参考成员很少是一个好主意-使用指针代替。

如果您在开始时大量插入,您可能需要
std::deque
,而不是
std::vector

,正如错误消息所说,您无法在活动对象中重新绑定引用,这就是默认情况下删除赋值的原因

除了在向量中存储指针外,您还可以以某种方式重写类:

I.使用指针而不是引用。它们非常有价值,就像在这个用例中:

#include <vector>

struct Nyan {
    int *x;
};

int main() {
    int x;
    std::vector<Nyan> v{{&x}, {&x}, {&x}};
    v.insert(v.begin(), Nyan{&x});
}
二,
std::reference_wrapper早在C++11中就引入了,以适应不可绑定性,允许在容器中存储引用:

#include <vector>
#include <functional>

struct Nyan {
    std::reference_wrapper<int> x;
};

int main() {
    int x;
    std::vector<Nyan> v{{x}, {x}, {x}};
    v.insert(v.begin(), Nyan{x});
}
#包括
#包括
结构年安{
标准::参考_包装器x;
};
int main(){
int x;
向量v{{x},{x},{x};
v、 插入(v.begin(),Nyan{x});
}

如果您有非静态引用成员变量,则类的复制赋值运算符将被隐式删除。你能做的是手动编写复制赋值操作符。为什么你需要一个非静态引用成员?顺便说一句,什么是
eggs
?@codekaizer My bad,我在这里使用了不完整的代码,所以我不必复制和粘贴整个代码。这只是用微分方程计算出的蜂王在这段时间内产卵的数量。@codekaizer我不想连续复制基因结构,因为考虑到我会有一整群同伙,这会占用很多内存。谢谢!我想我之前试过了,但不管什么原因都没用,但我会再试一次,让你知道。
struct Nyan {
    Nyan(int &x): x(&x) {}
private:
    int *x;
};
#include <vector>
#include <functional>

struct Nyan {
    std::reference_wrapper<int> x;
};

int main() {
    int x;
    std::vector<Nyan> v{{x}, {x}, {x}};
    v.insert(v.begin(), Nyan{x});
}