mat*_*121 1 c++ stdvector c++-standard-library
我有一个关于这个程序的问题。我是编程和 C++ 的初学者,我试图弄清楚两件事。
为什么这个程序没有编译(错误:使用未初始化的内存“总计” - 我将它定义为一个变量??)。
有人能解释一下 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;
}
Run Code Online (Sandbox Code Playgroud)
Run Code Online (Sandbox Code Playgroud)int userInput, n, total; . . . std::cout << sumUpTo(nums, total);
在这里,您声明total并直接将其用作sumUpTo函数的参数。在该函数中,您在比较 ( if (total > vec.size()))中使用它。但是,由于您从未在声明时对其进行初始化,也未在代码中的任何位置为其分配任何值,因此编译器不知道您所做的比较是什么,因为total它没有任何值。
有人能解释一下 main (sumUpTo) 之外的函数是如何工作的吗?特别是 '& vec' 和 'total'
sumUpTo声明为 - int sumUpTo(const std::vector<int>& vec, const std::size_t total)。
在这里,您期望该函数将整数向量作为参数。但是你可能对&vec 之前的那个有疑问。该符号仅指定您要将向量作为参考传递,而不是通过制作向量的完整副本。在我们的常规传递中,我们传递给函数的向量将作为原始向量的副本传递。但在这种情况下,向量被作为引用传递,而不是原始向量的副本。
请注意,我使用了术语引用而不是指针。如果您来自 C 背景,您可能会觉得两者相同,并且在某些情况下,它们的功能可能有点相似,但它们之间几乎没有差异(SO - 1 , 2 , 3上的一些很好的答案 ),您可以阅读网上有很多不错的资源。只需理解,在这种情况下,它会在将向量传递给函数时防止复制向量。如果函数声明没有提到该参数为const,您还可以在向量中进行更改,这些更改也将反映在原始向量中(如果您正常传递它而不是作为参考传递,则不会这样做)。
std::size_t是一种用于以字节为单位表示对象大小的类型。它是一种无符号数据类型,在处理对象大小时使用。如果您不确定和(这可能是您期望的总数)之间的区别,您也可以参考这个。std::size_tint
最后,很明显,const在函数中使用它是为了确保我们传递给函数的参数不会在函数中被修改。
| 归档时间: |
|
| 查看次数: |
77 次 |
| 最近记录: |