Vector of structs with const members?(具有 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 ofAssignable
types.
来自表 64(Assignable
要求):
From table 64 (Assignable
requirements):
在表64中,T
是用于实例化容器的类型,t
是T
的值,u
是(可能是 const
)T
的值.
In Table 64,
T
is the type used to instantiate the container,t
is a value ofT
, andu
is a value of (possiblyconst
)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 成员的结构向量?


基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16