c++ - 具体元素数量 - vector

标签 c++ algorithm sum stdvector c++-standard-library

我正在尝试打印出 vector 中前“x”元素的总和。基本上,用户输入一堆数字(这些数字被推回到 vector 中),一旦他们决定退出循环,他们就必须选择要求和的元素数量。

例如,如果他们输入“6, 5, 43, 21, 2, 1 ”,他们会选择想要求和的数字,例如“3”。最后,输出应该是“前3个数字的总和是”6、5和43是54

我发现的唯一的事情就是找到 vector 的总和,这(我相信)对我来说没有多大用处。

我还检查了一个 C++ 网站,其中 <vector>库,但无法确定是否有任何功能很有用。这是针对 C++ 的,请记住,我是一名新程序员。

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
    //  1) read in numbers from user input, into vector -DONE
    //  2) Include a prompt for user to choose to stop inputting numbers - DONE
    //  3) ask user how many nums they want to sum from vector -
    //  4) print the sum of the first (e.g. 3 if user chooses) elemens in vector.
    vector <int> nums;
    int userInput, n, total;

    cout << "Please enter some numbers (press '|' to stop input) " << endl;
    while (cin >> userInput) 
    {
        if (userInput == '|') 
        {
            break; //stops the loop if the input is |.
        }
        nums.push_back(userInput); //push back userInput into nums vector.
    }
    cout << "How many numbers do you want to sum from the vector (the numbers you inputted) ? " << endl;
    cin >> total;
    cout << nums.size() - nums[total]; //stuck here
    return 0;
}

最佳答案

您可以使用 std::accumulate 来自 <numeric> ,计算一个范围的总和,如下。

#include <numeric>  // std::accumulate
#include <vector>

int sumUpTo(const std::vector<int>& vec, const std::size_t total)
{
    if (total > vec.size()) 
    // if the index exceeds the vec size
    // return the sum of the conatining elelemnts or provide an exception
        return std::accumulate(vec.begin(), vec.end(), 0); 
    
    return std::accumulate(vec.begin(), vec.begin() + total, 0);
}

( See a demo )


还比较 int埃格尔与char这里

if (userInput == '|') 

当用户输入 124 时将会失败,因为(int)'|' == 124 。你需要重新考虑这部分。我的建议是询问用户他/她想要预先输入的元素数量,并仅为此运行循环。

也不要使用 using namespace std; 进行练习

关于c++ - 具体元素数量 - vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63318230/

相关文章:

c++ - 如何获取wxWidget窗口的 "non-maximzed"状态

c++ <未解析的重载函数类型>

jquery - Bootgrid 求和列并在页脚中显示结果

c++ - 将 std::vector<const Type*> 转换为 const std::vector<T, A> &Vec

java - 用于查找歌曲音调的音频分析器

c++ - 一端优先的随机算法

arrays - 如何解决具有递归关系作为数组元素的大和 10^18 的子集和问题

php - Array to SVG,灵活的PHP算法

javascript - 计算javascript中列的索引

mysql - 如果条件列为真则添加值