【问题标题】:sum of elements of a vector in range n1 n2一个向量在 n1 n2 范围内的元素之和
【发布时间】:2020-12-26 20:27:56
【问题描述】:

我想写一个函数calc(array, n1 , n2)

array 是一个整数向量。 n1n2 参数是由关系 0<= n1<= n2<array.size() 定义的整数。

calc 方法应该返回索引属于[n1; n2] 区间的数组的整数之和。

我尝试了这段代码,但它不正确

class Answer {


public:
    static int cal(const vector<int>& array, int n1, int n2) {


        int sum = 0;

        for (vector<int>::iterator it = array[0]+n1; it != array[0]+n2; ++it)
        {
            sum + = *it;
        }
        return sum;
    }

};

【问题讨论】:

  • 如果你想使用几乎相同的代码,你应该使用array.begin()而不是array[0]vector&lt;int&gt;::const_iterator而不是vector&lt;int&gt;::iterator,因为你通过一个常量引用传递它。

标签: c++ algorithm vector sum function-definition


【解决方案1】:

只需使用 &lt;numeric&gt; 标头中的 std::accumulate,如下所示:

int sum = std::accumulate(std::begin(array) + n1, 
                          std::begin(array) + n2 + 1, 0);

【讨论】:

  • 建议 std::accumulate 而不是循环是很好的建议。然而,一个理想的答案也可以解释 op 使用 array[0] 而不是 array.begin() 的错误。
  • 还应该提到std::accumulate在标题&lt;numeric&gt;中定义。
  • @Stef 好吧,cppreference 链接说得很清楚,但还是添加了。
【解决方案2】:

您可以使用标头&lt;numeric&gt; 中声明的标准算法std::accumulate

例如

#include <iterator>
#include <numeric>

//...

static int cal(const vector<int>& array, int n1, int n2) {
    return std::accumulate( std::next( std::begin( array ), n1 ),
                            std::next( std::begin( array ), n2 + 1 ),
                            0 );
}

注意,函数至少要像这样声明

static long long int cal(const vector<int>& array,
                         std::vector<int>::size_type n1, 
                         std::vector<int>::size_type n2) {
    return std::accumulate( std::next( std::begin( array ), n1 ),
                            std::next( std::begin( array ), n2 + 1 ),
                            0ll );
}

在这种情况下,溢出的风险会降低。

【讨论】:

  • 在这里使用std::next 有什么特别的原因吗?
  • @cigien 是的,这是有原因的。您将获得更通用的代码。例如,如果应该为 std::list 或 std::set 重写函数而不是 std::vector。
  • 好吧,这很合理。
猜你喜欢
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-03
  • 1970-01-01
  • 1970-01-01
  • 2021-04-20
  • 1970-01-01
  • 2021-10-23
相关资源
最近更新 更多