【发布时间】:2016-06-20 01:36:03
【问题描述】:
当我通过引用写入向量的函数传递std::vector<std::string> 时,被调用函数会修改向量,但调用函数看不到修改。
例如,在下面的代码中,oData 的大小为 20,而 data 的大小为 0。为什么?
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
bool ReadFile(const std::string & iFile, std::vector<std::string> & oData) {
std::ifstream myfile(iFile);
if (!myfile.is_open()) {
std::cout << "Unable to open file";
return false;
}
else {
std::string line;
while (getline(myfile, line)) {
std::cout << line << '\n';
oData.push_back(line);
}
myfile.close();
}
return true;
}
int main() {
std::vector<std::string> data;
ReadFile("numbers.txt", data);
return 0;
}
注意:在 Windows 10 上使用 Visual Studio 2015
【问题讨论】:
-
应该是
ReadFile("numbers.txt", data);,否则无法编译。 -
您发布的内容不可能是您测试的代码。这是Visual C++ online compiler test
-
那我们可以删除这个问题吗?
-
编辑修复错别字
-
@Ahmed 您的编辑只会使您的输入文件更有可能存在问题,即无法打开或为空。换句话说,
push_back()永远不会被执行。 See this
标签: c++ visual-studio vector fstream