我试图在向量中插入一个元素,但似乎我做错了.
这是我声明向量的地方:
std::vector<Dice> dicearray;
这是抛出错误的行:
dicearray.insert(dicearray.size()-1 ,Dice());
这些是抛出的错误:
Error (active) no instance of overloaded function "std::vector<_Ty, _Alloc>::insert [with _Ty=Dice, _Alloc=std::allocator<Dice>]" matches the argument list ConsoleApplication3 c:\Users\Miguel\Documents\Visual Studio 2015\Projects\ConsoleApplication3\ConsoleApplication3\ConsoleApplication3.cpp 60
和
Error C2664 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Dice>>> std::vector<Dice,std::allocator<_Ty>>::insert(std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<Dice>>>,unsigned int,const _Ty &)': cannot convert argument 1 from 'unsigned int' to 'std::_Vector_const_iterator<std::_Vector_val<std::_Simple_types<Dice>>>' ConsoleApplication3 c:\users\miguel\documents\visual studio 2015\projects\consoleapplication3\consoleapplication3\consoleapplication3.cpp 60
知道为什么会这样吗?
您需要为要插入的位置提供迭代器(请参阅参考资料:http://www.cplusplus.com/reference/vector/vector/insert/).错误基本上是说没有函数接受这些类型的参数(数字,元素).所以:
dicearray.insert(dicearray.end(), Dice()); // Insert element at the end (yes, without - 1)
Run Code Online (Sandbox Code Playgroud)
请注意,如果已经存在所需位置的元素,则从该位置到末尾的所有元素都将"向上"移位一个位置.
如果你只想添加元素,你可以使用push_back(然后你不指定位置,它被插入到最后位置):
dicearray.push_back(Dice());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1475 次 |
| 最近记录: |