如何使用std::vector.insert()
How to use std::vector.insert()?
所以,我正在尝试学习如何使用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));
相关文章:
- 为什么使用 <uint8_t>MSVC 2015 编译器的 std::vector::insert 比 std::copy 快 5 倍?
- 编译器如何区分"vector::insert"的两种变体?
- STL vector.insert 方法期望_InputIterator作为参数
- 排序时在空 std::vector 上使用 insert()
- map.insert:"Invalid arguments"错误与 pair<enum,vector<*>>
- 如何为我的自定义向量类实现类似 vector.insert 的方法
- Trouble with vector.insert()
- 重载分辨率如何适用于 std::vector:<int>:insert
- 将make_move_iterator与vector::insert一起应用有意义吗?(C++)
- 为什么std::vector::insert需要复制赋值
- C++错误: map.insert(make_pair(struct, vector<struct>));
- std::vector::insert 是否根据定义保留
- 如何使用std::vector.insert()
- std::vector.insert上的Seg故障
- std::move在vector::insert和push_back上的行为不同
- vector::insert在VS2010中执行意想不到的结果
- 为什么std::vector::insert复杂度是线性的(而不是常量)
- 是否允许 vector::insert 只保留一次,避免进一步的容量检查
- c++ vector insert访问违反读取位置
- Std::vector::insert给出意外的结果