【问题标题】:C++ Calling Vectors from Function to MainC++ 从函数调用向量到 Main
【发布时间】:2013-11-07 17:59:06
【问题描述】:

我正在尝试将大量值读入特定函数的向量中,然后将其调用到 main 中以获得平均值。我的 readInput 工作得很好。但我相信 当我 cout

using namespace std;
//function prototype
int readInput(vector<int> vect);


int main()
{
vector<int> values;
int sum, avg;
sum = readInput(values);

//cout << sum;

avg = sum / values.size();
cout << avg;

return 0;
}

int readInput(vector<int> vect)
{

int count;
int total = 0;

 ifstream inputFile("TopicFin.txt"); //open file

 if(!inputFile)
{
    return 0; // if file is not found, return 0
}

 while(inputFile >> count) //read file
 vect.push_back(count); //add to file

 for (int count = 0; count < vect.size(); count++)
 total+=vect[count]; //sum data in vector

return total;

}

【问题讨论】:

    标签: c++ vector


    【解决方案1】:

    您没有通过引用传递向量,因此您的函数仅将值存储在 main 向量的 副本中。

    int readInput(vector<int>& vect);
    

    这告诉您的程序通过 reference 传递向量,这意味着在函数中修改的任何内容都会直接修改 main 中的向量。如果您不熟悉这些内容,请查看 this post 解释参考和副本之间的区别。

    【讨论】:

    • 是的,做到了。我不敢相信我不认为通过引用传递。隧道视觉我的朋友。谢谢。
    【解决方案2】:

    您需要将向量作为引用或指针传递。该函数只是创建当前按值传递的向量的副本,并对其进行操作。

    将函数签名更改为 . . .

    int readInput(vector<int>& vect)
    

    或者(对于这个例子来说可能更奇怪)。 ..

    int readInput(vector<int> *vect)
    

    还将函数调用更改为

    sum = readInput(&values);
    

    【讨论】:

      【解决方案3】:

      虽然其他人已经提到了通过引用传递向量的可能性,但 不是 我认为在这种情况下我会这样做。我想我只是从函数中返回向量。我还将文件名传递给函数:

      std::vector<int> values = readInput("TopicFin.txt");
      

      至少对我来说,这似乎更好地反映了意图。也许我只是有点慢,但从名称上似乎一点也不明显readInput 的返回值将是它读取的值的总和。

      虽然返回向量理论上可能会导致编译器出现效率问题,该编译器既不支持移动构造也不支持返回值优化,但几乎可以保证任何此类编译器都非常古老,以至于您出于其他原因真的想避免它。

      就将数据读入向量而言,我会使用一对istream_iterators:

      std::vector<int> data{std::istream_iterator<int>(infile),
                            std::istream_iterator<int>()};
      

      当然,鉴于这很简单,我想知道是否值得拥有像 readInput 这样的单独函数。

      要对这些值求和,我会使用std::accumulate

      int total = std::accumulate(data.begin(), data.end(), 0);
      

      【讨论】:

        猜你喜欢
        • 2021-12-31
        • 2021-03-15
        • 1970-01-01
        • 2013-02-14
        • 2013-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多