【问题标题】:C++ vector passed by reference not modified通过引用传递的 C++ 向量未修改
【发布时间】: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


【解决方案1】:

问题在于 Visual Studio 调试器中的断点位置。

return 之后的断点 --> 数据大小 = 0; screenshot

return 之前的断点 --> 数据大小 = 实际大小。 screenshot

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多