C++ 从函数到 Main 调用 vector

标签 c++ vector

我正在尝试将大量值读入特定函数中的 vector ,然后将其调用到 main 中以获得平均值。我的 readInput 完美运行。但我相信 当我 cout << values.size(); 时,我的主函数返回 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;

}

最佳答案

您没有通过引用传递 vector ,因此您的函数仅将值存储在来自 main 的 vector 的拷贝中。

int readInput(vector<int>& vect);

这会告诉您的程序通过引用 传递 vector ,这意味着函数中的任何修改都会直接修改 main 中的 vector 。如果您不熟悉这些东西,请查看 this post解释引用和拷贝之间的区别。

关于C++ 从函数到 Main 调用 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19843253/

相关文章:

c++ - 如何让 IntelliSense 在 Visual Studio 2008 中可靠地工作

c++ - 为什么我不能使用 EGL 创建 headless OpenGl 上下文?

algorithm - 针对凸多面体形状类型转换胶囊

c++ - 如何在 C++ 中创建具有动态维度大小的数组?

c++ - 在 C++ 中通过引用修改此操作的开销是多少?

c++ - 用于 MSVC++ 2010 编译器的调试器

c++ - 如何在 WinAPI 中创建具有视觉样式的平面按钮

c++ - 在 CRichEdit 中使用 Alt+Unicode 更改插入的字符

c++ - 如何对 float 的多维 vector 进行排序?

c++ - 使用数组 vector 的正确方法