So, I'm trying to learn how to use std::vectors
, but I have a problem:
std::vector<Box>entities;
entities.insert(1, Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y), b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));
How come that doesn't work? It gives me the following error :
Error no instace of overloaded function "std::vector<_Ty, _alloc>::insert [with _Ty=Box, _Alloc=std::allocator<Box>] matches the argument list. Argument types are (int, Box). Object type is std::vector<Box, std::allocator<Box>>
What am I doing wrong?
The first parameter should be an iterator, not an index. You can get an iterator to position 1 by using entities.begin() + 1
.
Note that position 1 is the location of the second element in the vector: vector indexing is zero-based .
The first parameter is wrong. You should specify an iterator , not an index.
entities.insert(entities.begin() + i, theItem);
where i
is the position you want to insert at. Note that the vector must be at least of size i
.
entities.insert(entities.begin(), /*other stuff as before*/
would insert at the beginning of your vector. (ie the zeroth element). Remember that vector
indexing is zero-based.
entities.insert(1 + entities.begin(), /*other stuff as before*/
would insert at the second spot.
All overloaded versions of the method insert
require that the first argument would be of type std::vector<Box>::const_iterator
applied to your vector definition. This iterator specifies the position where a new element must be inserted.
However you are passing in an integer value 1 instead of the iterator
entities.insert(1,
^^^
Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));
There is no implicit conversion from an object of type int
to an object of type std::vector<Box>::const_iterator
. So the compiler issues an error.
Maybe you mean the following
#include <vector>
#include <iterator>
//...
entities.insert( std::next( entities.begin() ),
^^^^^^^^^^^^^^^^^^^^^^^^^^^
Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));
Or if your compiler does not support function std::next
then you can jjust write
entities.insert( entities.begin() + 1,
^^^^^^^^^^^^^^^^^^^^^
Box(&world, b2Vec2(Camera.getCenter().x, Camera.getCenter().y),
b2Vec2(25, 25), 0, sf::Color::Red, b2_dynamicBody, 1.0f, 0.3));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.