2

When I make a 2D vector. std::vector<std::vector<Pokemon>> pokemons;

Can I run this straight away: Pokemon pikachu = ... pokemons[23].push_back(Pikachu);

Or do I need to: pokemons.reserve(100); for (int i =0;i<100;i++) pokemons.push_back(vector<Pokemon>());

Thank you

trincot
  • 317,000
  • 35
  • 244
  • 286
JamesSin
  • 39
  • 3

3 Answers3

5

You can set the initial size of the outer vector during construction

std::vector<std::vector<Pokemon>> pokemons(100);

and it will build 100 inner empty vectors.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
  • Thanks, but how do I do it if I already declared it? For example: `std::vector> pokemons;` is already set somewhere else in the code. – JamesSin Nov 10 '17 at 14:15
  • The vector has a `resize` function you can use to give it a new size, both bigger and smaller than the current size. You can check the [cppreference.com](http://en.cppreference.com/w/cpp) for lots of C++ reference info. – Bo Persson Nov 10 '17 at 14:20
0

Can I run this straight away:

Pokemon pikachu = ...
pokemons[23].push_back(Pikachu);

Not straight away, because your pokemons array does not have any elements yet, so pokemons[23] will be an out-of-bounds error.

Otherwise, once your pokemons array is populated, then yes, you can just push_back on one of its elements.

Or do I need to:

pokemons.reserve(100);
for (int i =0;i<100;i++) pokemons.push_back(vector<Pokemon>());

reserve() is only to allocate (reserve) memory for your vector, if you have a good idea of how many elements you will end up having, to avoid multiple memory allocations and potential moves. You do not need to reserve(), but it is a good idea if you will need a decent amount of memory.

Infiltrator
  • 1,611
  • 1
  • 16
  • 25
0

Are you sure the vector is the most appropriate container you are looking for? Check How can I efficiently select a Standard Library container in C++11?

If '23' is really important, then you could for example use associative container:

 typedef std::map<int, pokemon> TPokemons;
 TPokemons pokemons;
 pokemons[23] = pikachu;

Maybe the order is not important and an unordered map would be better

CyanCoding
  • 1,012
  • 1
  • 12
  • 35
pierre.V
  • 16
  • 1
  • 3