【发布时间】:2020-08-08 19:13:43
【问题描述】:
我有一个关于这个程序的问题。在编程和 c++ 方面,我是初学者,我正在尝试弄清楚两件事。
-
为什么这个程序没有编译(错误:使用未初始化的内存'total' - 我把它定义为一个变量??)。
-
有人能解释一下 main (
sumUpTo) 之外的函数是如何工作的吗?特别是& vec和total,因为我以前从未见过它们。谢谢。
/* 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) elements in vector.*/
#include <iostream>
#include <string>
#include <vector>
#include <numeric> //for accumulate
int sumUpTo(const std::vector<int>& vec, const std::size_t total)
{
if (total > vec.size())
return std::accumulate(vec.begin(), vec.end(), 0);
return std::accumulate(vec.begin(), vec.begin() + total, 0);
}
int main()
{
std::vector<int> nums;
int userInput, n, total;
std::cout << "Please enter some numbers (press '|' to stop input) " << std::endl;
while (std::cin >> userInput) {
if (userInput == '|') {
break; //stops the loop if the input is |.
}
nums.push_back(userInput); //push back userInput into nums vector.
}
std::cout << "How many numbers do you want to sum from the vector (the numbers you inputted) ? " << std::endl;
std::cout << sumUpTo(nums, total);
return 0;
}
【问题讨论】:
-
您已经声明了
total,并且您正在使用它,但您从未赋予它任何特定的价值。然后,您的程序会通过访问未初始化的对象来表现出未定义的行为。 -
sumUpTo你不清楚吗?您似乎在说您以前从未见过带参数的函数。你最喜欢的 C++ 教科书肯定包含这样的例子。 -
@IgorTandetnik 我已经看到他们采用了参数,但不是这样处理我认为是 & 的指针。并且尚未讨论 main 之外的调用函数,因此我的问题是先生。
-
&这里表示引用,而不是指针。你最喜欢的 C++ 教科书应该有一节关于通过引用传递参数。还有一个关于定义和调用函数的部分。 -
是的,我相信确实如此,但是这本书是为完全的初学者准备的,我认为他试图强迫我们使用简单的编码技能(简单的函数等),不过我会研究一下,谢谢你。
标签: c++ stdvector c++-standard-library