提问人:Saleh 提问时间:8/28/2021 最后编辑:Alan BirtlesSaleh 更新时间:8/28/2021 访问量:122
使用向量时 [] 运算符的问题
problem with [] operator when using a vector
问:
我正在尝试为 Game 制作一个复制构造函数。在整个复制构造函数中,我必须将一个游戏的元素复制到另一个游戏中。但是,当我尝试访问要复制的游戏内部时,我收到一个错误,说:
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)
我将不胜感激任何帮助解释为什么 [] 运算符不起作用,这是我写的一段代码:
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]; ///////???
}
}
除此之外,我还想问一下,使用“new”来分配游戏是否更好,或者只是像我在上面的代码段中所做的那样声明它。
答:
1赞
Alan Birtles
8/28/2021
#1
向量的运算符需要一个参数。您正在传递迭代器,这就是它不编译的原因。[]
size_t
other[row][col]
可以只用 替换为 。 有点棘手,你不能使用 和 迭代器,因为它们来自不同的容器。您可以通过从 中减去迭代器来将迭代器转换为数字索引,例如: 。这很难阅读,因此最好为每个容器使用两个单独的迭代器,或者只对两个容器使用索引。*col
game[row][col]
row
col
game
begin
other[row - other.game.begin()][col - row->begin()]
更好的解决方案是让标准库为您完成工作:
std::copy(other.game.begin(), other.game.end(), game.begin());
无需逐个复制内部向量的元素,将一个向量分配给另一个向量即可为您进行复制。
评论
other
game
game