0
votes

For some reason, resizing this two dimensional vector in my class does not work. Thanks for your help!

..
Map::Map(const unsigned int& w,
         const unsigned int& h,
         const unsigned int& s)
    : width(w), height(h), size(s)
{
    squares.resize(width);
    for (unsigned int i = 0; i < width; ++i)
    {
        squares[i].resize(height); // error here
        for (unsigned int j = 0; j < height; ++j)
        {
            squares[i][j] = Square(sf::Vector2f(i * size, j * size));
        }
    }
}

std::vector<std::vector<Square>> squares;
..

Some error messages:

c:\mingw\bin..\lib\gcc\mingw32\4.6.2\include\c++\bits\stl_uninitialized.h|481| instanziiert von »static void std::__uninitialized_default_n_1<TrivialValueType>::_uninit_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Square*, _Size = unsigned int, bool _TrivialValueType = false]«|

c:\mingw\bin..\lib\gcc\mingw32\4.6.2\include\c++\bits\stl_uninitialized.h|529| instanziiert von »void std::__uninitialized_default_n(_ForwardIterator, _Size) [with _ForwardIterator = Square*, _Size = unsigned int]«|

1
Does Square have a default constructor?Peter
consider using boost::multi_array instead of nested vectorsaryan
Yes, it has a default constructor: Square(const sf::Vector2f& pos);user1429101
default constructor is a constructor that takes no arguments. what you posted is a constructor that needs one argument and therefore should be marked explicit to avoid implicit conversionsaryan
@aryjczyk multi_array is, by name, an array, not a vectorBartek Banachewicz

1 Answers

1
votes

When you vector.resize(n) and n > vector.size() you are asking it to create n - vector.size() new elements. Vector needs to default construct them, since he doesn't know what arguments to use. If they are not default constructible, resize fails.

However, if you don't want Square to be default constructible you can change failing line to vector.reserve() - that only makes sure there is enough space for new elements, but doesn't actually create them. Then you can create them one by one in a loop using

squares[i].emplace_back(sf::Vector2f(i * size, j * size));

Oh, and by the way passing primitives by reference has suboptimal performance. Pass them by value unless you need them as out parameters.