gpt4 book ai didi

c++ - 在 C++ 中将文本文件插入 std::string 的数组/集合的最佳方法是什么

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:11:16 26 4
gpt4 key购买 nike

What is the best way to read an entire file into a std::string in C++?的风格我想问一个类似的问题,除了我希望我的输出是一个包含文本文件中的行的数组/STL 容器。

C#/.net 有相当有用的 File.ReadAllLines()效用函数,好的 C++ (STL) 版本应该是什么样的?

最佳答案

在 C++ 中,您可以这样做。

  • 将结构定义为:

    struct line : std::string 
    {
    friend std::istream & operator >> (std::istream & in, line & ln)
    {
    return std::getline(in, ln);
    }
    };
  • 然后这样做:

    std::ifstream file("file.txt");
    std::istream_iterator<line> begin(file), end;
    std::vector<std::string> allLines(begin, end);
  • 完成!

通过这种方法,您可以直接使用迭代器对 beginend .无需使用 std::vector<std::string> .注意 line可以隐式转换为 std::string .所以你可以使用 beginend使用标准算法。

例如,

  • 找到最长的线:

    auto cmp = [](line const &a, line const& b) { return a.size() < b.size(); };
    std::string longestLine = *std::max_element(begin, end, cmp);
  • 统计长度大于10的行数:

    auto cmp = [](line const &a) { return a.size() > 10 ; };
    size_t count = std::count_if(begin, end, cmp);
  • 等等。这样,您可以直接使用 begin 工作和 end .无需使用 std::vector .节省内存。

希望对您有所帮助。

关于c++ - 在 C++ 中将文本文件插入 std::string 的数组/集合的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14561349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com