4

I have a vector of structs that contain a vector, and i don't know how to initialize the fields inside the struct. I have the following code:

struct member {
  vector<pair<int, int> > rival_result;
  int matches;
}
vector<member> ranking(n);

I want to set the size of the vector inside the struct to the size of the other vector and have 0 in all the fields(matches and the integers of the pair vector). N can be a very big number so it can't be done manually. Thanks.

flapedriza
  • 342
  • 2
  • 12
  • C++11 or later allowed? Also, can the size change after initialisation / must it be set at runtime? – Deduplicator May 18 '14 at 13:56
  • Can't use c++ 11, and the size can't change after the initialization, for more info, this code is a private member of a class and i ned to initialize it on 0 for the creator function which is: Ranking::Ranking(int n); – flapedriza May 18 '14 at 14:08

1 Answers1

4

Write a constructor for member first that sets the size of your vector:

struct member {
    explicit member (int n) : rival_result(n), matches(0) { }
    vector<pair<int, int> > rival_result;
    int matches;
};

Now create your vector:

vector<member> ranking(n, member(n));
T.C.
  • 133,968
  • 17
  • 288
  • 421
  • Thanks, i didn't know about the explicit specifier, tomorrow i will ask my teacher if i can use it on my code, they are very restrictive about we can ad can't use. – flapedriza May 18 '14 at 15:45
  • @flapedriza Using `explicit` is optional here. It prevents the compiler from treating the constructor as defining an implicit conversion from `int` to `member`, which can be the source of bugs. [This question](http://stackoverflow.com/questions/121162/what-does-the-explicit-keyword-in-c-mean) has the details. – T.C. May 18 '14 at 16:07