具有 const 成员的结构向量? [英] Vector of structs with const members?

查看:16
本文介绍了具有 const 成员的结构向量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有

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

struct Student
{
    const string name;
    int grade;
    Student(const string &name) : name(name) { }
};

那么,我该如何保留学生的向量?

How do I, then, keep a vector of students?

int main()
{
    vector<Student> v;

    // error C2582: 'operator =' function is unavailable in 'Student'
    v.push_back(Student("john"));
}

有没有办法做到这一点,或者我必须在堆上分配所有学生,并改为存储指向每个学生的指针?

Is there even a way to do this, or must I allocate all the students on the heap, and store a pointer to each of them instead?

推荐答案

你不能.您的类型违反了可分配";对标准容器的要求.

You can't. Your type violates the "Assignable" requirement for standard containers.

ISO/IEC 14882:2003 23.1 [lib.container.requirements]/3:

ISO/IEC 14882:2003 23.1 [lib.container.requirements] / 3:

这些组件中存储的对象类型必须满足CopyConstructible的要求types (20.1.3),以及 Assignable 类型的附加要求.

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

来自表 64(Assignable 要求):

From table 64 (Assignable requirements):

在表64中,T是用于实例化容器的类型,tT的值,u 是(可能是 const)T 的值.

In Table 64, T is the type used to instantiate the container, t is a value of T, and u is a value of (possibly const) T.

表达式:t = u;返回类型:T;后置条件:t 等价于 u

expression: t = u; return type: T; post-condition: t is equivalent to u

理论上,std::vector 等价物可以选择在所有情况下进行销毁和复制构造,但这不是已选择的合约.如果不需要重新分配,则对 vector::operator=vector::assign 等内容使用包含类型的赋值运算符可能会更有效.

In theory, a std::vector equivalent could choose to do destruction and copy construction in all cases, but that's not the contract that has been chosen. If reallocation isn't required, then using the contained type's assignment operator for things like vector::operator= and vector::assign might be significantly more efficient.

这篇关于具有 const 成员的结构向量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆