4

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[] ?

Guillaume Racicot
  • 36,309
  • 8
  • 69
  • 115
monzie
  • 555
  • 5
  • 14
  • 2
    unrelated: `typedef struct { ... } name;` is unecessary in C++ since `struct name { ... };` is enough to use `name` as a type (no `struct` needed like in C) – YSC Jan 22 '18 at 15:44
  • Not a good duplicate. The complexity here is that the vector element is a user defined type. – Bathsheba Jan 22 '18 at 15:48
  • @Holt: Feel free to submit an answer based on that "copy paste", and see how it performs in the voting. – Bathsheba Jan 22 '18 at 16:04
  • @Holt: No I wouldn't downvote on that basis. I would downvote if the answer wasn't useful in my opinion, and upvote if the converse were true, which it might be. My mind is open on that point. – Bathsheba Jan 22 '18 at 16:10

2 Answers2

4

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 structs pre-C++11.

It was for precisely these constructs that the C++11 syntax was developed.

Bathsheba
  • 227,678
  • 33
  • 352
  • 470
2

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";
}

live demo

YSC
  • 36,217
  • 8
  • 89
  • 142
  • But you cannot do like that in pre-c++11 `Data dd[] = { make_data({3, 2, 4}, 1) };` - I mean necessity to define extra arrays - it is something not really "elegant"?. – PiotrNycz Jan 22 '18 at 16:32