Home > Net >  problem with [] operator when using a vector
problem with [] operator when using a vector

Time:09-17

I'm trying to make a copy constructor for Game. throughout the copy constructor I have to copy the elements of one game into another. However when I try to access the inner elemnts of the game I want to copy I get an error saying :

no operator "[]" matches these operands -- operand types are: mtm::Game [ std::_Vector_const_iterator<std::_Vector_val<std::conditional_t<true, std::_Simple_types<std::vector<char, std::allocator<char>>>, std::_Vec_iter_types<std::vector<char, std::allocator<char>>, size_t, ptrdiff_t, std::vector<char, std::allocator<char>> *, const std::vector<char, std::allocator<char>> *, std::vector<char, std::allocator<char>> &, const std::vector<char, std::allocator<char>> &>>>> ]C/C  (349)

I'd appreciate any help with explaining why the [] operator doesn't work, here's the piece of code I wrote :

Game::Game(const Game& other)
{
    Game game(other.height, other.width);

    for (vector<vector<char>>::const_iterator row = other.game.begin(); row != 
                                                              other.game.end(); row  )
    {
        for(vector<char>::const_iterator col = row->begin(); col != row->end(); col  )
        {                
            game[row][col] = other[row][col];  ///////???
        }
    }

In addition to that, I'd like to ask if it's better to allocate a game using "new" or just declare it like I did in my code segment above.

CodePudding user response:

The [] operator of a vector expects a size_t argument. You are passing an iterator which is why it doesn't compile.

other[row][col] can be replaced with just *col. game[row][col] is a little more tricky, you can't use the row and col iterators with game as they are from a different container. You can convert the iterators to numeric indexes by subtracting them from begin, e.g.: other[row - other.game.begin()][col - row->begin()]. This gets quite hard to read so you might be better off either using two separate iterators for each container or just using indexes for both containers.

The better solution is to let the standard library do the work for you:

std::copy(other.game.begin(), other.game.end(), game.begin());

There is no need to copy the elements of the inner vector one by one, assigning a vector to another one does the copying for you.

  • Related