![](/img/trans.png)
[英]Why is std::stack using 18 times more memory than std::vector when used as an element of a vector?
[英]Why does skipping occurs when using std::remove() to remove more than one value from a vector?
我正在做一个挑战 ,那天晚上我偶然发现了Reddit,而您一天要进行一次编程挑战。 看起来真的很不错,并且在我学习的同时为自己提供了很多练习。
我遇到了一个问题,我尝试使用std::remove()
从向量中删除某些内容,并删除了所需的数字,这就是问题所在,即其后的下一个数字。 我尝试过执行其他功能和各种方式来执行此操作,但这似乎是最实用的,并且感觉非常接近我的需求。
#include <iostream>
#include <algorithm> // std::sort(), std::remove()
#include <vector>
void print_array(std::vector<int> array)
{
std::cout << "Array: ";
for(int i = 0; i < array.size(); i++)
{
std::cout << array.at(i) << " ";
}
std::cout << std::endl;
}
int main()
{
std::vector<int> num_array = {2, 3, 4, 2, 3, 5, 4, 6, 4, 6, 9, 10, 9, 8, 7, 8, 10, 7};
// Sort ant then print the array.
std::sort(num_array.begin(), num_array.end());
print_array(num_array);
for(int i = 0; i < num_array.size(); i++)
{
if(num_array.at(i) == num_array.at(i + 1))
{
std::cout << num_array.at(i) << " is duped\n";
num_array.erase(std::remove(num_array.begin(), num_array.end(), num_array.at(i)), num_array.end());
print_array(num_array);
}
else
{
std::cout << num_array.at(i) << " is not duped.\n";
}
}
print_array(num_array);
return 0;
}
即使您刚刚删除了元素,也可以增加索引。 如果不删除元素,则只想增加索引。
请注意,您的算法需要O(N 2 )时间,而有可能以O(N)复杂度实现此功能。 另外, std::vector<T>::at()
是可憎的,最好不要使用! 最好的情况是浪费时间,最坏的情况下会掩盖错误。
remove
使用const引用将要删除的东西,并假设它在整个删除过程中都没有改变。
您的代码违反了该假设。 例如,在第一次迭代中,您通过引用将num_array[0]
传递给remove
,但是该元素很快就会被后面的元素(值为3
)覆盖,然后所有后续比较都被弄乱了,因为它们最终使用了新价值。
使用一元+
强制复制:
num_array.erase(std::remove(num_array.begin(), num_array.end(), +num_array[i]),
num_array.end());
然后,您将看到DietmarKühl的答案中指出的问题 。 也解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.