C++ 删除向量中包含相同项的一项
想象一下,你有一个C++ 删除向量中包含相同项的一项,c++,string,vector,C++,String,Vector,想象一下,你有一个vector目录,里面装满了apples和oranges。如何删除向量中的单个apple而不是所有applesstd::remove通常会这样做,因为据我所知,字符串是相同的。我认为这条线需要改变 inventory.erase(remove(inventory.begin(), inventory.end(), "apple") inventory.end()); 您只需找到第一个,如果它存在,请删除它 如前所述,您可以使用和轻松删除一个实例 当一个项从向量中消失,并位于中
vector目录
,里面装满了apple
s和oranges
。如何删除向量中的单个apple
而不是所有apple
sstd::remove
通常会这样做,因为据我所知,字符串是相同的。我认为这条线需要改变
inventory.erase(remove(inventory.begin(), inventory.end(), "apple") inventory.end());
您只需找到第一个,如果它存在,请删除它
如前所述,您可以使用和轻松删除一个实例
当一个项从向量中消失,并位于中间某个位置时,它的所有项必须向左移动一个时隙,这意味着<代码> o(n)< /代码>复杂性。如果不关心向量中元素的顺序,可以通过将最后一个组件移动到要移除的位置,然后移除向量的最后一个位置,将复杂性降低到
O(1)
:
auto it = std::find(std::begin(inventory), std::end(inventory), apple);
if (it != std::end(inventory)) {
*it = std::move(inventory.back());
inventory.pop_back();
}
在这种情况下,更好的方法是通用模板函数,因此您可以将其用于不同的类型:
template<class Container>
inline auto remove_first_coincidence(Container &container, typename Container::value_type const& element) {
auto it = std::find(std::begin(container), std::end(container), element);
if (it != std::end(container)) {
*it = std::move(container.back());
container.pop_back();
return true;
}
return false;
}
模板
内联自动删除\u第一个\u重合(容器和容器,typename容器::值\u类型常量和元素){
autoit=std::find(std::begin(容器)、std::end(容器)、元素);
if(it!=std::end(容器)){
*it=std::move(container.back());
container.pop_back();
返回true;
}
返回false;
}
所以。。。不要使用
删除。使用find
查找apple
和vector::erase
。在remove\u first\u concurrence()
中,需要通过引用而不是通过值传递容器,否则您将修改容器的副本而不是原始副本。您需要在演示中更改这一点。对不起,我从一个使用迭代器的旧通用实现中复制了代码:这是一个小错误。
auto it = std::find(std::begin(inventory), std::end(inventory), apple);
if (it != std::end(inventory)) {
*it = std::move(inventory.back());
inventory.pop_back();
}
template<class Container>
inline auto remove_first_coincidence(Container &container, typename Container::value_type const& element) {
auto it = std::find(std::begin(container), std::end(container), element);
if (it != std::end(container)) {
*it = std::move(container.back());
container.pop_back();
return true;
}
return false;
}