gpt4 book ai didi

c++ - vector 和函数练习

转载 作者:行者123 更新时间:2023-12-01 15:10:15 25 4
gpt4 key购买 nike

我对此程序有疑问。在编程和C++方面,我是一个初学者,我试图弄清楚两件事。

  • 为什么该程序无法编译(错误:使用未初始化的内存“总计”-我已将其定义为变量?)。
  • 可以解释一下main(sumUpTo)之外的功能如何工作吗?特别是& vectotal,因为我从未见过它们。谢谢。
  • /* 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;
    }

    最佳答案

    您的代码中的错误-


  • int userInput, n, total;
    .
    .
    .
    std::cout << sumUpTo(nums, total);

    在这里,您声明了total并将其直接用作sumUpTo函数的参数。在该函数中,您正在比较中使用它(if (total > vec.size()))。但是,由于您从未在声明时初始化它,也从未在代码中的任何地方分配任何值,因此编译器不知道如何进行比较,因为total没有任何值。

  • could someone explain how the function outside of main (sumUpTo)works? Specifically '& vec' and 'total'

    sumUpTo的声明为- int sumUpTo(const std::vector<int>& vec, const std::size_t total)
    在这里,您期望该函数将整数 vector 作为参数。但是您可能会对vec之前的 &感到怀疑。该符号仅表示您将转到 pass the vector as a reference,而不是通过完整复制该 vector 。在常规传递中,传递给函数的 vector 将作为原始 vector 的副本传递。但是在这种情况下, vector 将作为引用传递,而不是原始 vector 的副本。
    请注意,我使用的 ,而不是指针。如果您来自C背景,您可能会觉得两者相同,并且在某些情况下,它们的功能可能有些相似,但是它们之间几乎没有区别( 关于- 123的一些不错的答案)可以阅读许多在线可用的好资源。只需了解在这种情况下,它就可以防止在将 vector 传递给函数时复制该 vector 。如果函数声明中没有提到该参数为 const,那么您还可以在 vector 中进行更改,这也将反射(reflect)在原始参数中(但如果您正常地传递它而不是将其作为引用,它们就不会有此变化) 。 std::size_t是一种类型,用于表示对象的大小(以字节为单位)。它是无符号数据类型,在处理对象大小时使用。如果不确定 std::size_tint(这可能是您期望的总数)之间的差异,也可以引用 this
    最后,很明显在函数中使用了 const,以确保传递给函数的参数不会在函数中被修改。

    关于c++ - vector 和函数练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63319341/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com