在某个值的元素之前插入std::向量中的元素
Inserting an element in a std::vector before element of certain value
你能建议一种更好的方法在std::vector:中的另一个值之前插入一个值吗
template<class T>
void insert(std::vector<T>& container, const T& valueToInsertBefore, const T& valueToInsert)
{
std::vector<T>::iterator i = container.begin();
std::vector<T>::iterator end = container.end();
for(;i!=end;++i)
{
if(*i==valueToInsertBefore)
{
i = container.insert(i, valueToInsert);
i++;
end = container.end();
}
}
}
更新:
应为std::矢量中找到的每个valueToInsertBefore实例插入。
使用std::find()
来定位值,而不是显式循环:
std::vector<T>::iterator i = v.begin();
while (v.end() != (i = std::find(i, v.end(), valueToInsertBefore)))
{
// insert() returns an iterator to the inserted element.
// The '+ 2' moves past it and the searched for element.
//
i = v.insert(i, valueToInsert) + 2;
}
std::vector
可能会因为需要重新分配而变得相当低效,以防它相当大和/或之前要插入的元素经常出现。使用这样的副本的一种更简单的方法可能会对CPU更友好(以需要更多内存为代价):
template<class T>
void insert(std::vector<T>& container,
const T& valueToInsertBefore,
const T& valueToInsert)
{
std::vector<T> result;
result.reserve( container.size() );
std::vector<T>::const_iterator it, end = container.end();
for ( it = container.begin(); it != end; ++it ) {
if ( *it == valueToInsertBefore ) {
result.push_back( valueToInsert );
}
result.push_back( *it );
}
container.swap( result );
}
container.insert(std::find(container.begin(), container.end(), valueToInsertBefore), valueToInsert);
您最好更改容器,列表更适合此类操作。使用插入时,可能会使迭代器和指针失效,并且还需要重新分配内存。
http://www.cplusplus.com/reference/stl/vector/insert/
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 我想访问std::unique_ptr中的一个特定元素
- 如何从存储在std::映射中的std::集中删除元素
- 缓存std::数组的选定元素,并在c++中自动保持其一致性
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 为什么在 std::map 上移动无法将元素从一个映射移动到另一个映射
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- std::矢量保存 只推送最后一个元素
- std::map:当元素不可默认构造时创建/替换元素
- 如何读/写或遍历 std::array 中的特定元素范围?
- C++如何乘以包含 std::variant 元素的向量的迭代器?正在执行迭代器类型的转换?
- 为什么 std::p air 的大小与其元素的大小之和不同?
- 我可以列表初始化 std::vector 并完美转发元素吗?
- 如何打印属于地图的一系列元素(std::p air<size_t,std::string>)(不是所有元素)
- 元素 std::vector <struct>的更有成效的段落
- 不能直接分配元素 std::array,它说没有运算符"="匹配
- 如何到达 2d std::vector 的第 N 个元素('std::vector< std::vector<T> >')?