c++ - 如何将大文件读入 vector 或数组

标签 c++

我编写了将文件读取为 vector 的代码。 但速度非常慢。(读取大约430000行需要12秒) 我的代码有什么问题吗? 当我在 C# 中做同样的事情时,只需要 0.5 ~ 1 秒。

#include <iostream>
#include <string>
#include <fstream>
#include <vector>

using namespace std;

bool getFileContent(string fileName, vector<string> &vecOfStrs)
{
    ifstream in(fileName.c_str());

    if (!in)
    {
        std::cerr << "Cannot open the File : " << fileName << std::endl;

        return false;
    }

    string str;

    while (getline(in, str))
    {
        if (str.size() > 0)
        {
            vecOfStrs.push_back(str);
        }
    }

    in.close();

    return true;
}

int main()
{
    string my_file_path = "C:/Users/user/Desktop/myfile.txt";
    vector<string> lines;
    bool result = getFileContent(my_file_path, lines);

    if (result)
    {
        cout << lines.capacity() << endl;
    }
}

最佳答案

我假设您正在使用 Visual Studio 来开发您的应用程序。 执行以下步骤优化为/O2

1> 项目属性 --> 配置属性 --> C/C++ --> 代码生成 --> 基本运行时检查 = 默认

2> 项目属性 --> 配置属性 --> C/C++ --> 优化 --> 优化 = 最大优化(优先速度)(/O2)

这将使您的程序在运行时得到最大程度的优化。 如果仍然不好,我认为你应该使用此链接计算文件中的行数 How to count lines of a file in C++?

并保留该数字作为初始 vector 的容量。

希望它能解决您的问题。这是我的解决方案

ifstream in("result_v2.txt");
vector<string> lines;
string str;

while (std::getline(in, str))
{
    if (str.size() > 0)
    {
        lines.push_back(str);
    }
}

in.close();

关于c++ - 如何将大文件读入 vector 或数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54489442/

相关文章:

c++ - Qt程序错误

c++ - C++ 中的 Zip 目录

c++ - 要使用的类初始化括号

c++ - 一个变量中的最大指针数

c++ - SFML 2.1 网络

c++ - 使用 C++ 函数中的汇编器为循环编码

c++ - cmake 和 GenerateExportHeader

c++ - 从 char 到 const* char 的无效转换,代码有什么问题?

c++ - 类内的 ZMQ C++ 事件循环

c++ - 处理 Win 7 应用程序中的限制