Reputation: 236
The following prints "1\n 1\n 1" as expected. Can I construct "ar" in a way that it will print "2\n 2\n 2" without giving it an explicit initializer list (... ar = {A(2), A(2), A(2)})?
#include <iostream>
#include <array>
class A {
public:
A(int i=1) : m_i(i) {};
int m_i;
};
int main() {
std::array<A, 3> ar;
for(auto& v : ar) {
std::cout << v.m_i << std::endl;
}
}
Upvotes: 2
Views: 34
Reputation: 157374
Not really; array
doesn't have any interesting constructors like vector
's vector(size_type, T = T())
.
The closest you can get is to use fill
, possibly with an initializing lambda:
std::array<A, 3> ar = []{ std::array<A, 3> ar; ar.fill(2); return ar; }();
Upvotes: 1