c++ - 在 list<int> 或 vector<int> 中添加备用数字

标签 c++ list vector

我正在尝试访问列表中的替代数字以添加它们的值。对于,例如如果 List 的值 = { 1, 2, 3, 5}。我应该得到输出,4 和 7。

为此,我使用了 std::List。首先,我需要能够访问序列的第 N 个元素 std::list 才能添加值。也就是说,我知道我可以使用 std::advance 获取第 N 个元素的迭代器:

std::list<Object> l;

unsigned N = /* index of the element that I want to retrieve */;
if (l.size() > N)
{
    std::list<Object>::iterator it = l.begin();
    std::advance(it, N);
}

但是,这并没有解决我的问题,因为我不明白如何在添加备用值时访问它们,因为它不提供随机访问。

因此,我尝试使用我正在使用的 std::vector

sum_of_vector =std::accumulate(vector.begin(),vector.end(),0);

当我添加 vector 的所有值时,这很有效,但如果我只需要添加 std::list 的替代值,我不明白其中的逻辑>std::vector.

最佳答案

请看下面的代码。我已经添加了评论,以便它不言自明。

#include <bits/stdc++.h>
using namespace std;

int main() 
{
    //Your vector of integers
    vector<int> V = {1, 2, 3, 5};

    //Size of your vector
    int n = V.size();

    //Initialise two integers to hold the final sum
    int sum1 = 0;
    int sum2 = 0;

    //Calculate sum1 starting from first element and jumping alternate element until you reach end
    for(int i=0; i<n; i+=2)
        sum1 += V[i];

    //Calculate sum2 starting from second element and jumping alternate element until you reach end
    for(int i=1; i<n; i+=2)
        sum2 += V[i];

    //Print your answer
    cout << "Sum1 = " << sum1 << " " << "Sum2 = " << sum2 << endl;

    return 0;
}

关于c++ - 在 list<int> 或 vector<int> 中添加备用数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31331746/

相关文章:

list - F# 列表中的 Task.WaitAll

c# - 什么更快?缓存大量对象或通过 IEnumerable 访问它们?

c++ - 将 vector 传递给函数

math - 给定一个轴的向量,如何找到其他两个轴的向量?

C++ 数组初始化

c++ - 为什么 cout << *s << endl 会产生段错误?

python - 为什么添加到列表会做不同的事情?

c++ - 引用二维 vector 中的元素 (c++)

c++ - CreateFile 返回无效句柄值

c++ - 如何部署依赖动态库的应用程序?