0

Let's say I have a 2D vector:

std::vector<std::vector<int>> world;

I want to achieve something like this:

world[0][0] = x;
world[0][1] = y;
etc

So I came up with this function:

int Controller::AddBody(SDL_Rect RECT, SDL_Color COLOR)
{
    world[world.size() + 1].push_back(RECT.x);
    world[world.size() + 1].push_back(RECT.y);
    world[world.size() + 1].push_back(RECT.w);
    world[world.size() + 1].push_back(RECT.h);
    world[world.size() + 1].push_back(COLOR.r);
    world[world.size() + 1].push_back(COLOR.g);
    world[world.size() + 1].push_back(COLOR.b);
    world[world.size() + 1].push_back(COLOR.a);

    return world.size() + 1;
}

however this creates an exception. I can't understand why?

2 Answers2

2

This is a more modern approach to the accepted answer utilizing the new emplace methods added in C++11 and an initializer list:

int Controller::AddBody(SDL_Rect RECT, SDL_Color COLOR)
{
     world.emplace_back(std::vector<int>{
        RECT.x, 
        RECT.y, 
        RECT.w, 
        RECT.h, 
        COLOR.r, 
        COLOR.g, 
        COLOR.b, 
        COLOR.a
    });
    return world.size() + 1;
}

Live demo

M2tM
  • 4,415
  • 1
  • 34
  • 43
Shoe
  • 74,840
  • 36
  • 166
  • 272
  • That gives me the error `could not deduce template argument for '_Valty &&' from 'initializer-list'` – user3806521 Jul 04 '14 at 20:56
  • @user3806521 See [this recent question](http://stackoverflow.com/questions/24550924/emplacement-of-a-vector-with-initializer-list/24551018#24551018). – juanchopanza Jul 04 '14 at 20:58
1

world[world.size() + 1] will point off the end of the vector (one beyond world.end()).

Look back at what your world vector really represents: A vector of vectors. So for each new entry in your world[] vector, you want to add a new vector.

The code should look like this:

int Controller::AddBody(SDL_Rect RECT, SDL_Color COLOR)
{
    std::vector<int> newVec;

    newVec.push_back(RECT.x);
    newVec.push_back(RECT.y);
    newVec.push_back(RECT.w);
    newVec.push_back(RECT.h);
    newVec.push_back(COLOR.r);
    newVec.push_back(COLOR.g);
    newVec.push_back(COLOR.b);
    newVec.push_back(COLOR.a);
    world.push_back(newVec);

    return world.size();
}

Keep in mind that when working with std::vector, the [] operator only allows access to an element that already exists in the array. So if your array is only 3 elements, and you try to set the 4th, you'll get an exception. You always have to either resize the vector or push a new element into the vector to create a new element.

stix
  • 1,140
  • 13
  • 36