繁体   English   中英

C ++调用从函数到主函数的向量

[英]C++ Calling Vectors from Function to Main

我正在尝试将大量值读入特定函数中的向量,然后将其调用到main中以获得平均值。 我的readInput工作得很好。 但我相信当我输入<< values.size();时,我的main函数返回0。 为什么是这样? 我该怎么做才能改变它?

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;

}

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

int readInput(vector<int>& vect);

这告诉你的程序通过引用传递向量意味着函数中修改的任何东西直接在main中修改你的向量。 如果你对这个东西不熟悉,请查看这篇文章,解释参考和复制之间的区别。

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

将功能签名更改为。

int readInput(vector<int>& vect)

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

int readInput(vector<int> *vect)

也改变了函数调用

sum = readInput(&values);

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

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

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

虽然返回一个向量理论上可能导致编译器既不支持移动构造也不支持返回值优化的效率问题,但是任何这样的编译器都非常保证是如此古老,以至于你真的想要出于其他原因而避免使用它。

至于将数据读入向量,我会使用一对istream_iterator

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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM