Let's say I have
#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 const individual members of a struct. Declaring an entire instance of a struct with a const qualifier is the same as creating a special-purpose copy of the struct with all members specified as const .
You can actually create a vector of structs!
If we desire that the elements of a vector should not be modified, we can declare that vector as a const vector. However, we must initialize this vector when it is declared, as it is not possible to modify it subsequently. Thus, a const vector can be declared and initialized as shown below.
You can't put items into a const vector, the vectors state is the items it holds, and adding items to the vector modifies that state. If you want to append to a vector you must take in a non const ref.
You can't. Your type violates the "Assignable" requirement for standard containers.
ISO/IEC 14882:2003 23.1 [lib.container.requirements] / 3:
The type of objects stored in these components must meet the requirements of
CopyConstructible
types (20.1.3), and the additional requirements ofAssignable
types.
From table 64 (Assignable
requirements):
In Table 64,
T
is the type used to instantiate the container,t
is a value ofT
, andu
is a value of (possiblyconst
)T
.expression:
t = u
; return type:T
; post-condition:t
is equivalent tou
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.
The simple answer is: you can't. If you have const
member variables, then the compiler can't supply a default copy-assignment operator. However, many of the operations that std::vector
provides need to make assignments, and therefore require a (public) copy-assignment operator.
Your options are:
name
non-const
.const
member.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With