我正試圖為Game制作一個復制構造器。在整個復制構造器中,我必須將一個游戲的元素復制到另一個游戲中。
沒有運算子"[]"匹配這些運算子--運算子型別為:tmm::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 "來分配一個游戲,還是像我上面的代碼段那樣直接宣告好呢?
uj5u.com熱心網友回復:
[] 向量的操作器期望一個size_t的引數。你傳遞的是一個迭代器,這就是為什么它不能被編譯的原因。
other[row][col]可以用*col來代替。game[row][col]就比較麻煩了,你不能用row和col的迭代器,因為它們是來自不同的容器。你可以通過從begin中減去這些迭代器來轉換為數字索引,例如。other[row - other.game.begin()][col - row-> begin()]。這將變得相當難以閱讀,所以你最好為每個容器使用兩個單獨的迭代器,或者只為兩個容器使用索引。
更好的解決方案是讓標準庫為你做這些作業:
std::copy(other.game. begin(), other.game.end(), game.begin())。)
不需要逐一復制內部向量的元素,將一個向量分配給另一個向量就可以完成復制。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/314162.html
標籤:
上一篇:當試圖訪問shared_ptr的向量時,operator[]的問題
下一篇:C 中條件變數的問題
