Reputation: 565
I am using gcc version 4.9.2 If I compile using the compiler flag -std=c++0x the following code compiles OK.
#include <iostream>
#include <vector>
using namespace std;
typedef struct
{
vector<int> a;
int b;
} MYTYPE;
int main(void)
{
MYTYPE test[]=
{
{ {1,2,3},4},
{ {5,6},7},
{ {},8}
};
}
If I remove the -std=c++0x flag then the compiler reports:
error: could not convert ‘{1, 2, 3}’ from ‘’ to ‘std::vector’
What is an elegant way to initialize test[] ?
Upvotes: 4
Views: 2209
Reputation: 40070
With C++98, the best one can achive is probably the definition and use of an helper function:
struct Data
{
std::vector<int> vector;
int scalar;
};
template<std::size_t N>
Data make_data(const int (&vector)[N], int scalar)
{
Data result;
result.vector.assign(vector, vector+N);
result.scalar = scalar;
return result;
}
int main()
{
const int vector[] = {1,2,3}; // just to annoy people using namespace std :)
Data d = make_data(vector, 4);
std::cout << d.vector[2] << "\n" << d.scalar << "\n";
}
Upvotes: 3
Reputation: 234665
Other than achieving some semblance of elegance at the calling site by writing a set of hideous constructors in your struct
, there is no particularly elegant way of initialising an array of these struct
s pre-C++11.
It was for precisely these constructs that the C++11 syntax was developed.
Upvotes: 4