向量的const与const成员? [英] Vector of structs with const members?

查看:135
本文介绍了向量的const与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
类型的要求.3)以及可分配类型的附加要求。

64(可分配需求):


在表64中, T 是用于实例化容器的类型, t T 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与const成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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