有指针时使用 std::accumulate
using std::accumulate when there is pointer
当有一个指向向量的指针并且我们想使用 accumulate 对数字求和时,this 是唯一的解决方案吗?
有没有比编写 lambda 函数并使用四参数类型的累积更简单的解决方案?
还有,使用std::sort
,情况会一样吗?
代码如下:
#include <random>
#include <vector>
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
const int N=3;
auto p=make_unique<array<int,N>> ();
(*p)[0]=3;
(*p)[1]=4;
(*p)[2]=5;
sum=accumulate(p,?,0);
return 0;
}
回答您的直接问题:
std::accumulate(p->begin(), p->end(), 0);
相同的语法也适用于其他 STL 算法。
代码段的其他改进:
避免使用 #include<bits/stdc++.h>
、. Similarly for using namespace std
,这被认为是不好的做法。
const N=3
-> const auto N=3
std::array
不是向量,您可以使用初始化列表语法直接初始化它:
const auto* obj = new std::array<int,3>{3,4,5};
当有一个指向向量的指针并且我们想使用 accumulate 对数字求和时,this 是唯一的解决方案吗? 有没有比编写 lambda 函数并使用四参数类型的累积更简单的解决方案?
还有,使用std::sort
,情况会一样吗?
代码如下:
#include <random>
#include <vector>
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
int main() {
const int N=3;
auto p=make_unique<array<int,N>> ();
(*p)[0]=3;
(*p)[1]=4;
(*p)[2]=5;
sum=accumulate(p,?,0);
return 0;
}
回答您的直接问题:
std::accumulate(p->begin(), p->end(), 0);
相同的语法也适用于其他 STL 算法。
代码段的其他改进:
避免使用 #include<bits/stdc++.h>
、using namespace std
,这被认为是不好的做法。
const N=3
-> const auto N=3
std::array
不是向量,您可以使用初始化列表语法直接初始化它:
const auto* obj = new std::array<int,3>{3,4,5};