我正在尝试删除数组中与特定情况匹配的所有元素。 例如..
if(ar[i]==0)
delete all elements which are 0 in the array
print out the number of elements of the remaining array after deletion
我尝试了什么:
if (ar[i]==0)
{ x++; } b=N-x; cout<<b<<endl;
只有当我每次都想删除一个元素并且我不知道如何在我需要的情况下删除时才有效。 我假设我需要遍历数组并选择找到的元素的所有实例并删除出现的所有实例。 不是每次出现只增加一次“x”变量,是否有可能在一定次数的情况下将它增加一定次数?
编辑(有人要求我粘贴我所有的代码):
int N; cin>>N; int ar[N]; int i=0; while (i<N) { cin>>ar[i]; i++; }//array was created and we looped through the array, inputting each element. int a=0; int b=N; cout<<b; //this is for the first case (no element is deleted) int x=0; i=0; //now we need to subtract every other element from the array from this selected element. while (i<N) { if (a>ar[i]) { //we selected the smallest element. a=ar[i]; } i=0; while (i<N) { ar[i]=ar[i]-a; i++; //this is applied to every single element. } if (ar[i]==0) //in this particular case, we need to delete the ith element. fix this step. { x++; } b=N-x; cout<<b<<endl; i++; } return 0; }
整个问题可以在这里找到: Cut-the-sticks
最佳答案
您可以使用 std::remove
函数。
我本来打算写一个例子来配合链接,但是链接中的例子几乎是我要发布的内容,所以这里是链接中的例子:
// remove algorithm example
#include <iostream> // std::cout
#include <algorithm> // std::remove
int main () {
int myints[] = {10,20,30,30,20,10,10,20}; // 10 20 30 30 20 10 10 20
// bounds of range:
int* pbegin = myints; // ^
int* pend = myints+sizeof(myints)/sizeof(int); // ^ ^
pend = std::remove (pbegin, pend, 20); // 10 30 30 10 10 ? ? ?
// ^ ^
std::cout << "range contains:";
for (int* p=pbegin; p!=pend; ++p)
std::cout << ' ' << *p;
std::cout << '\n';
return 0;
}
严格来说,发布的示例代码可以优化为不需要指针(特别是如果您使用任何标准容器类型,如 std::vector
),还有 std::remove_if
函数这允许为更复杂的谓词逻辑传递额外的参数。
然而,您提到了 Cut the sticks challenge
,我认为您实际上不需要使用任何删除功能(除了正常的容器/数组删除功能)。相反,您可以根据挑战中设置的条件使用类似以下代码的内容来“切割”和“删除”(即从棍子上切割 X,然后如果 < 0 则删除并打印每次通过的切割次数):
#include <iostream>
#include <vector>
int main () {
// this is just here to push some numbers on the vector (non-C++11)
int arr[] = {10,20,30,30,20,10,10,20}; // 8 entries
int arsz = sizeof(arr) / sizeof(int);
std::vector<int> vals;
for (int i = 0; i < arsz; ++i) { vals.push_back(arr[i]); }
std::vector<int>::iterator beg = vals.begin();
unsigned int cut_len = 2;
unsigned int cut = 0;
std::cout << cut_len << std::endl;
while (vals.size() > 0) {
cut = 0;
beg = vals.begin();
while (beg != vals.end()) {
*beg -= cut_len;
if (*beg <= 0) {
vals.erase(beg--);
++cut;
}
++beg;
}
std::cout << cut << std::endl;
}
return 0;
}
希望对您有所帮助。
关于c++ - 如何在给定 if 条件的情况下删除整数数组中的特定元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34507221/