C++ 元素的特定数量-向量

C++ 元素的特定数量-向量,c++,algorithm,sum,stdvector,c++-standard-library,C++,Algorithm,Sum,Stdvector,C++ Standard Library,我试图打印出向量中第一个“x”元素的和。基本上,用户输入一组数字(被推回向量),一旦他们决定退出循环,他们就必须选择要求和的元素数 例如,如果他们输入“6、5、43、21、2、1”,他们会选择希望求和的数字,例如“3”。最后,输出应该是“前3个数字的总和是”6、5和43是54” 我所发现的唯一一件事就是找到向量的和,我相信这对我没有多大用处 我还用C++代码网站检查了< >代码>库,但是不能计算出任何函数都有用。这是C++的,记住,我是一个新程序员。 #include <iostream&

我试图打印出向量中第一个“x”元素的和。基本上,用户输入一组数字(被推回向量),一旦他们决定退出循环,他们就必须选择要求和的元素数

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

我所发现的唯一一件事就是找到向量的和,我相信这对我没有多大用处

<>我还用C++代码网站检查了< >代码>库,但是不能计算出任何函数都有用。这是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;
int main()
{
//1)将用户输入的数字读入向量-完成
//2)包括提示用户选择停止输入数字-完成
//3)询问用户希望从向量求和多少num-
//4)打印向量中第一个(如用户选择3个)元素的总和。
向量nums;
int userInput,n,总计;
cout(用户输入)
{
如果(userInput='|')
{
break;//如果输入为|,则停止循环。
}
push_back(userInput);//将userInput推回到nums向量中。
}
cout-total;
cout您可以使用,来计算范围的和,如下所示

#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);
}
当用户输入
124
时将失败,因为
(int)|'==124
。您需要重新考虑此部分。我的建议是询问用户希望预先输入的元素数,并仅为此运行循环

也不要练习使用

您可以使用from header,如下所示

std::cout << std::accumulate(nums.begin(), nums.begin()+total,0);

std::cout如果(userInput=''.')
真的工作了,那么它就不工作了?你确定你正在读取所有的值吗?如果用户想输入整数版本的
,会发生什么情况?试着给出
124
,如果你的系统使用Shift\u JIS或UTF-8(或其他ASCII兼容字符代码),它将停止读取输入我还检查了一个C++网站,它使用了@ CigiEn:我用它测试了这个程序,这个循环在用户按下之前输入用户输入,所以它确实有效(尽管我可能写的代码坏了)。@MikeCAT谢谢,我知道这一点。但是,我正在做的练习告诉我要使用“int”数据类型,所以我想我暂时坚持使用它。感谢你的详细回答,JeJo。主要代码块是我应该在main中调用的函数吗?我还看到很多人忽视了“使用名称空间std”,但建议初学者使用。。我想我现在就用std::谢谢!@matiboy212121是的,需要在main之外定义函数并像这样调用:
cout向量的大小,直接调用
cout返回
-1
很奇怪。如何区分
-1
的和?如果没有足够的元素?@cigien好的,谢谢我这么做了,但是出于某种原因,“total”没有定义,尽管我把它和其他变量一起列出了。。。
std::cout << std::accumulate(nums.begin(), nums.begin()+total,0);