Reputation: 114
I'm trying to insert an element in a vector but it seems I'm doing something wrong.
Here's where I declare the vector:
std::vector<Dice> dicearray;
This is the line that throws the errors:
dicearray.insert(dicearray.size()-1 ,Dice());
And these are the error that are thrown:
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
and
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
Any idea why this is happening?
Upvotes: 1
Views: 5014
Reputation: 1508
You need to provide an iterator to the position you want to insert it to (see reference: http://www.cplusplus.com/reference/vector/vector/insert/). The error is basically saying there's no function which takes these types of arguments (number, element). So:
dicearray.insert(dicearray.end(), Dice()); // Insert element at the end (yes, without - 1)
Note that, if there's an element at the desired position already, all elements from that location to the end are shifted one position "up".
If you just want to add the element, you can use push_back
(and then you don't specify the position, it's inserted in the last position):
dicearray.push_back(Dice());
Upvotes: 7