我创建了类并在私有(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/