如何使用std::vector.insert()

How to use std::vector.insert()?

本文关键字:insert vector std 何使用      更新时间:2023-10-16

所以,我正在尝试学习如何使用std::vectors,但我遇到了一个问题:

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));

为什么不起作用?它给了我以下错误:

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>>

我做错了什么?

第一个参数应该是迭代器,而不是索引。您可以使用entities.begin() + 1使迭代器位于位置1。

请注意,位置1是向量中第二个元素的位置:向量索引是基于零的

第一个参数错误。您应该指定迭代器,而不是索引。

entities.insert(entities.begin() + i, theItem);

其中i是要插入的位置。请注意,矢量的大小必须至少为i

entities.insert(entities.begin(), /*other stuff as before*/将插入到向量的开头。(即第零个元素)。请记住,vector索引是基于零的。

entities.insert(1 + entities.begin(), /*other stuff as before*/将插入第二点。

方法insert的所有重载版本都要求第一个参数的类型为应用于向量定义的std::vector<Box>::const_iterator。此迭代器指定必须插入新元素的位置。

但是,您传入的是整数值1,而不是迭代器

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));

不存在从int类型的对象到std::vector<Box>::const_iterator类型的对象的隐式转换。因此编译器会发出一个错误。

也许你指的是下面的

#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));

或者,如果你的编译器不支持函数std::next,那么你可以只写

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));