I read that if I want to define array of elements from a type T
, so class T
must a default c'tor (It's correct, yes?).
But what about defining container (from the STL) of elements from type T
?
I read that if I want to define array of elements from a type T
, so class T
must a default c'tor (It's correct, yes?).
But what about defining container (from the STL) of elements from type T
?
You don't need default constructors in both cases.
#include <iostream>
#include <vector>
struct A
{
int x;
A(int x) : x(x) {}
};
int main()
{
A arr[3] {A(0), A(1), A(2)}; // An array
std::vector<A> vec; // A std container
vec.push_back(A(0));
vec.push_back(A(1));
vec.push_back(A(2));
}
Though, for some containers the lack of default constructor disables some operations, like operator[]
of std::map
and std::unordered_map
.