2

您能否建议一种在 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::vector 中找到的每个 valueToInsertBefore 实例插入。

4

4 回答 4

4

用于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;
}
于 2012-09-17T08:47:49.867 回答
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 );
}
于 2012-09-17T09:30:05.520 回答
1
container.insert(std::find(container.begin(), container.end(), valueToInsertBefore), valueToInsert);
于 2012-09-17T08:46:40.810 回答
0

你最好改变容器,列表更适合这种操作。使用插入,您有使迭代器和指针无效的风险,并且您还需要重新分配内存。

http://www.cplusplus.com/reference/stl/vector/insert/

于 2012-09-17T08:50:49.650 回答