【问题标题】:c++ STL remove-if algorithm and erase algorithm issue.c++ STL remove-if 算法和擦除算法问题。
【发布时间】:2016-06-12 15:27:02
【问题描述】:

目标:创建一个向量。使用 remove_if 就可以了

#include<iostream>
#include<vector>
#include<iterator>
#include<algorithm>
#include<functional>
using namespace std;
int main()
{
    int negative_count=0;
    vector<int> v = { 2, -1, -3, 5, -5, 0, 7 };
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    cout << endl;

    vector<int>::iterator new_it=remove_if(v.begin(), v.end(), bind2nd(greater<int>(), -1));
    v.erase(new_it);
    copy(v.begin(), v.end(), ostream_iterator<int>(cout, " "));
    cout << endl;


}

输出:

remove_if 条件是删除大于 -1 的数字。 为什么它显示 -5 两次?根据我的说法, remove_if 之后的输出应该是 -1 -3 -5 5 0 7 。 另外,如果我使用

V.erase(new_int,v.end())

输出很好:-1 -3 -5

【问题讨论】:

标签: c++ vector stl


【解决方案1】:

当您调用std::remove/remove_if 时,它会将不满足条件的元素移动到范围的前面。未指定任何剩余元素的值(从返回的迭代器的位置开始)。有些人似乎认为它交换了元素,使得满足条件的元素被移到后面。但该算法并未指定执行此操作。如果这是您想要的结果,那么您正在寻找的算法是std::partition

【讨论】:

    【解决方案2】:

    信息说replace_if返回一个指向新范围的指针,所以我期望输出后的新范围

    1. remove_if 返回一个迭代器

    即一个结束迭代器,该范围仅包含不满足条件的元素。无法保证该范围的其余部分将包含所有其他元素。

    std::vector<int> v{ 2, -1, -3, 5, -5, 0, 7 };
    auto new_end = std::remove_if(v.begin(), v.end(), [](auto i){ return i > -1; });
    
    // now the range [v.begin(), new_end) contains only elements that are not > -1
    // contents of [new_end, v.end()) are unspecified
    
    for(auto i = v.begin(); i!=new_end; ++i)
    {
        std::cout << *i;
    }
    
    1. erase-remove 习惯用法要求您指定要删除的整个元素范围。

    那是因为您需要删除所有符合条件的项目。不止一个。

    v.erase(new_end, v.end());
    

    【讨论】:

      【解决方案3】:

      擦除元素从向量中删除单个元素 (位置) 或一系列元素 ([first,last))。

      以上参考来自http://www.cplusplus.com/reference/vector/vector/erase/ 这意味着在您的情况下,您只需从 remove_if() 函数返回的迭代器指向的向量中删除一个元素。您需要定义最后提到的范围:

      V.erase(new_int,v.end())
      

      【讨论】:

        【解决方案4】:

        因为 remove_if 实际上并没有删除任何东西,它只是将满足谓词的元素复制/移动到最后。所以你必须写v.erase(new_it, v.end())Link

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-03-27
          • 1970-01-01
          • 1970-01-01
          • 2020-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多