从数组中删除所有大于n的元素

5

我是一个编程新手,有些东西让我难以编写。假设,我有一个数组。

int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};

我想要删除所有大于9的元素。我该如何实现这个目标?

1
你不能从数组中删除元素。你能做的最好的事情是将它们设置为一些特殊的值。 - juanchopanza
1
你编写代码时遇到了困难,因为无法从数组中删除项目。 - PaulMcKenzie
1
可能是从C++数组中删除元素的重复问题。 - trejder
@trejder,谢谢。但我想在条件下删除元素。 - Xrin
3个回答

11
你可以使用向量来做到这一点。首先使用你的数组初始化向量,然后使用remove_if()函数。希望这能帮到你。
#include <algorithm>
#include <vector>

int main()
{
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};

vector<int> V(Array, Array+20);
vector<int> :: iterator it;

it = remove_if(V.begin(), V.end(), bind2nd(greater<int>(), 9));


V.erase (it, V.end());  // This is your required vector if you wish to use vector

}

如果无法从数组中删除元素,那么我将尝试使用这个...谢谢。 - Xrin
1
为什么要有 int K?这是不必要的。V.erase(it, V.end()); - PaulMcKenzie
@PaulMcKenzie,哦..谢谢。 - Shahriar

6

由于数组大小固定,您无法从数组中删除项目。

如果您使用了std::vector,则解决方案如下:

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

  using namespace std;

  int main()
  {
     std::vector<int> Array = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};

     Array.erase(remove_if(Array.begin(), Array.end(), [](int n) { return n > 9; }),
                 Array.end());
     copy(Array.begin(), Array.end(), ostream_iterator<int>(cout, " "));

  }

实时示例:http://ideone.com/UjdJ5h

如果您想坚持使用数组,但标记大于10的项,可以使用相同的算法std::remove_if

  #include <algorithm>
  #include <iostream>
  #include <iterator>

  using namespace std;

  int main()
  {
     int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
     int *overwrite_start = remove_if(std::begin(Array), std::end(Array), [](int n){ return n>9; });
     fill(overwrite_start, std::end(Array), -1);
     copy(std::begin(Array), std::end(Array), ostream_iterator<int>(cout, " "));
  }

上面的代码会将“被删除”的项移动到数组末尾,并用-1标记它们。
实时示例:http://ideone.com/7rwaXy 请注意两个示例中STL算法函数的使用。数组的第二个示例使用相同的remove_if算法函数。remove_if返回“删除”数据的开头,因为remove_if实际上并不删除,而是将数据移动到序列的末尾。

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Jarod42
为了对称,您也可以使用std :: begin() - Jarod42

1
我正在尝试在不使用向量的情况下交换概念。
int Array[] = {3,6,9,5,10,21,3,25,14,12,32,41,3,24,15,26,7,8,11,4};
int n;
int arr_len = sizeof(Array)/sizeof(int);
void print_array_value() {
int i;
cout << "\n";
for (i = 0; i < arr_len; i++) {
    cout << Array[i] << ", ";
}
cout << " : " << arr_len << "\n";
}
void swap_array_value(int start) {
int i;
for ( ; (start+1) < arr_len; start++) {
    Array[start] = Array[start+1];
}
}
void remove_array_value() {
int i;
for (i = 0; i < arr_len; i++) {
    if (Array[i] > n) {
        swap_array_value(i);
        arr_len--;
        i--;
    }
}
}
void main () {
clrscr();
cout << "Enter the N value : ";
cin >> n;
print_array_value();
remove_array_value();
print_array_value();
cout << "Array Length : " << arr_len;
getch();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接