gpt4 book ai didi

c++ - C++ 中的 accumulate(a.begin(), a.end(), 0) 和 accumulate(a.begin(), a.end(), 0ll) 之间有什么区别吗?

转载 作者:行者123 更新时间:2023-12-02 18:27:49 27 4
gpt4 key购买 nike

当我写作时
long long sum = accumulate(a.begin(), a.end(), 0);
或者
long long sum = accumulate(a.begin(), a.end(), 0ll);
两者都给我相同的结果(其中 astd:: vector<int> a(n) )。

那么为什么要使用 0ll而不仅仅是 0

这是我的代码:

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e6;
int main()
{
#ifdef _DEBUG
freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
#endif

int n;
cin >> n;
vector<int> a(n);
vector<int> cnt(MAX + 1);
for (int i = 0; i < n; ++i)
{
cin >> a[i];
++cnt[a[i]];
}
long long sum = accumulate(a.begin(), a.end(), 0ll);
vector<int> ans;
for (int i = 0; i < n; ++i)
{
sum -= a[i];
--cnt[a[i]];
if (sum % 2 == 0 && sum / 2 <= MAX && cnt[sum / 2] > 0)
{
ans.push_back(i);
}
sum += a[i];
++cnt[a[i]];
}

cout << ans.size() << endl;
for (auto it : ans)
cout << it + 1 << " ";
cout << endl;
return 0;
}

这里是 the same code on OnlineGDB

最佳答案

std::accumulate是一个模板,当传入0(应该是sum的初始值)时,第二个模板参数会被推导为int,那么sum就是在int上执行,返回类型也是int。然后在long long sum = accumulate(a.begin(), a.end(), 0);中,将返回的int转换为long long 并分配给 sum

另一方面,accumulate(a.begin(), a.end(), 0ll);long long 求和并返回一个很长很长

如果总和不会导致 int 溢出,那么在这两种情况下您将得到相同的结果。否则,应该优先考虑第二个。

关于c++ - C++ 中的 accumulate(a.begin(), a.end(), 0) 和 accumulate(a.begin(), a.end(), 0ll) 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69849548/

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