c++ - 我应该如何使用remove_if删除两个数字范围内的元素

标签 c++ algorithm vector stl remove-if

我创建了类并在私有(private)字段内初始化了一个 vector ,然后我使用类的方法初始化了 vector 。 现在我需要删除必须在键盘上输入的两个数字范围内的元素

#include <iostream>
#include <vector>
#include <algorithm>

int randomNumber()
{
    return (0 + rand() % 50 - 10);
}

class Array {
vector<int>::iterator p;
public:
    vector<int>array;
    Array(int size)
    {
        array.resize(size);
        generate(array.begin(), array.end(), randomNumber);
    }
    void Print() {
        for (p = array.begin(); p != array.end(); p++) {
            cout << *p << ' ';
        }
        cout << endl;
    }
    void Condense() {
        int a, b;
        cout << "Enter your range: [";  
        cin >> a;
        cin >> b;
        cout << "]" << endl;
        for (p = array.begin(); p != array.end(); p++) {
            if (a < *p < b || a > *p < b) {

            }
        }
    }
};

最佳答案

这是一个演示程序,展示了如何删除 ( a, b ) 范围内的 vector 元素。

#include <iostream>
#include <vector>
#include <tuple>
#include <iterator>
#include <algorithm>

int main() 
{
    std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    int a = 7, b = 2;

    std::tie( a, b ) = std::minmax( { a, b } );

    auto inside_range = [&]( const auto &item )
    {
        return a < item && item < b;
    };

    v.erase( std::remove_if( std::begin( v ), std::end( v ), inside_range ),
             std::end( v ) );

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

它的输出是

0 1 2 3 4 5 6 7 8 9 
0 1 2 7 8 9 

您可以编写如下条件,而不是使用 std::minmax 和 std::tie 来排序 a 和 b

    auto inside_range = [&]( const auto &item )
    {
        return a < item && item < b || b < item && item < a;
    };

至于您的代码,则 if 语句中的条件

if ( a < *p < b || a > *p < b) {

不正确,你的意思是

if (a < *p && *p < b || b < *p && *p < a ) {

关于c++ - 我应该如何使用remove_if删除两个数字范围内的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58267235/

相关文章:

c++ - 我需要/如何释放 wstring、wstringstream、 vector

c++ - 线程安全 vector 实现

c++ - 如何实现 "InterpolatedVector"?

c++ - C++中通过第一个对象创建第二个对象时,第一个对象到哪里去了?

c++ - 将字符串的 c_str 的结果转换为 char* 是否安全?

algorithm - 计算开口支架的最大深度

algorithm - 以最少的时间访问图中的 N 条特殊边

c++ - for循环错误计算素数C++

c++ - ADL 在 constexpr 函数中不起作用(仅限 clang)

java - 将 List<Map<String, List<String>>> 转换为 String[][]