gpt4 book ai didi

c++ - 如果我在 std::remove 函数中直接传递数组元素 ar[0] 而不是 x,为什么会得到不同的结果?

转载 作者:行者123 更新时间:2023-12-01 14:05:53 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





std::remove() works as expected with literal but not with dereferenced iterator

(2 个回答)


去年关闭。



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

using namespace std;

int main()
{
vector<int> ar = {1, 2, 2, 2, 3, 4, 5, 5, 5, 6, 7};
vector<int> sum;
int n = ar.size();
for (int i = 0; i < n; i++)
{
int x = ar[0];
int frq = count(ar.begin(), ar.end(), x);
int q = frq / 2;
sum.push_back(q);

ar.erase(remove(ar.begin(), ar.end(), x), ar.end()); // Doubt
}
int count = 0;
int n1 = sum.size();
for (int i = 0; i < n1; i++)
{
count = count + sum[i];
}
cout << count;
}
如果不是 x,为什么我会得到不同的结果我直接通过 ar[0]std::remove功能? xar[0]具有相同的值(value)。

最佳答案

原因是std::remove通过引用获取最后一个参数。来自 cppreference :

Because std::remove takes value by reference, it can have unexpected behavior if it is a reference to an element of the range [first, last).


这有点棘手,因为参数被传递为 const引用:
template< class ForwardIt, class T >
ForwardIt remove( ForwardIt first, ForwardIt last, const T& value );

然而,仅仅因为 ar[0]被传递为 const引用并不意味着 ar[0]不能通过其他方式修改。在这种情况下,它是通过 first 修改的。/ last .实际上,我想不出在 [first, last) 中包含元素是“可以”的情况。如 value .
例如,请考虑使用 ar[0] 得到相同的错误输出。就好像你声明了 x作为引用:
int& x=ar[0];
ar.erase(remove(ar.begin(),ar.end(),x),ar.end());
这里 x被传递为 const引用,但算法确实修改了 ar[0] .

关于c++ - 如果我在 std::remove 函数中直接传递数组元素 ar[0] 而不是 x,为什么会得到不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63487413/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com