在某个值的元素之前插入std::向量中的元素

Inserting an element in a std::vector before element of certain value

本文关键字:元素 std 向量 插入      更新时间:2023-10-16

你能建议一种更好的方法在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/