C++ 中的向量和设计策略

发布于 2024-09-12 23:01:43 字数 626 浏览 1 评论 0原文

可能的重复:
std::vector 中的元素总和

我想对 std::vector 的项目求和

例如

 std::vector<int > MYvec;
 /*some push backs*/

 int x=sum(MYVec); //it should give sum of all the items in the vector

如何编写 sum 函数?

我已经尝试过

 int sum(const std::vector<int> &Vec)
 {
    int result=0;
    for (int i=0;i<Vec.size();++i)
      result+=Vec[i];
    return result;
 }

但是我不喜欢我的方法

Possible Duplicate:
sum of elements in a std::vector

I want to sum the items of a std::vector

For example

 std::vector<int > MYvec;
 /*some push backs*/

 int x=sum(MYVec); //it should give sum of all the items in the vector

How to write sum function?

I have tried this

 int sum(const std::vector<int> &Vec)
 {
    int result=0;
    for (int i=0;i<Vec.size();++i)
      result+=Vec[i];
    return result;
 }

However I don't like my approach

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

拥有 2024-09-19 23:01:43

尝试使用 C++ 标准库中的 accumulate
像这样的事情:

#include <vector>
#include <numeric>

// Somewhere in code...
std::vector<int> MYvec;
/*some push backs*/

int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );

Try to use accumulate from C++ standard library.
Something like this:

#include <vector>
#include <numeric>

// Somewhere in code...
std::vector<int> MYvec;
/*some push backs*/

int sum = std::accumulate( MYvec.begin(), MYvec.end(), 0 );
巾帼英雄 2024-09-19 23:01:43

您应该使用std::accumulate

int main() {
  std::vector<int> vec;
  // Fill your vector the way you like
  int sum = std::accumulate(vect.begin(), vect.end(), 0); // 0 is the base value
  std::cout << sum << std::endl;
  return 0;
}

You should use std::accumulate.

int main() {
  std::vector<int> vec;
  // Fill your vector the way you like
  int sum = std::accumulate(vect.begin(), vect.end(), 0); // 0 is the base value
  std::cout << sum << std::endl;
  return 0;
}
℡Ms空城旧梦 2024-09-19 23:01:43

是否有一个 std::accumulate 函数可以做到这一点?

Isent there a std::accumulate function that does this?

凉薄对峙 2024-09-19 23:01:43

您必须迭代数组中的所有项目并计算总和,没有更简单的方法。我想 for 循环是最简单的

int sum = 0;
for(unsigned i = 0; i < Myvec.size(); i++){
   sum += MYvec[i];
}

You have to iterate over all the items in the array and compute the sum, there is no easier way. I guess for cycle is the simplest

int sum = 0;
for(unsigned i = 0; i < Myvec.size(); i++){
   sum += MYvec[i];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文