gpt4 book ai didi

c++ - 在文件上实现迭代器

转载 作者:行者123 更新时间:2023-12-01 14:36:41 27 4
gpt4 key购买 nike

我想创建一个带有加载文件的类,并为给定的类实现一个迭代器,以使用范围迭代器对其进行迭代

这是我的课

class Csv
{

public:
explicit Csv(std::string filepath);
~Csv();
void load_new_file(std::string filepath) {}

private:
std::ifstream file;
};

这是我要实现的行为

Csv csv("path");
for (auto line : csv ){
std::cout<<line<<std::endl;
}

我该怎么做?

最佳答案

使用 std::getline 的最小示例:

class End_iterator {};

class Iterator {
public:
Iterator(std::ifstream& file) : file_{file} {
next();
}

const std::string& operator*() const {
return str_;
}

Iterator& operator++() {
next();
return *this;
}

bool operator!=(End_iterator) const {
return !!file_;
}

private:
void next() {
std::getline(file_, str_);
}

std::ifstream& file_;
std::string str_;
};

class Csv {
public:
explicit Csv(std::string filepath) {
file_.open(filepath);
}

auto begin() {
return Iterator{file_};
}

auto end() {
return End_iterator{};
}

private:
std::ifstream file_;
};

C++17 允许我们在基于范围的 for 循环中使用不同类型的 beginend 迭代器。使 End_iterator 成为独特的类型(哨兵)会更容易(也更优雅)。

关于c++ - 在文件上实现迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62716242/

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