实现逻辑
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
int main() {
std::ifstream file("example.csv"); // 替换为你的CSV文件路径
if (!file.is_open()) {
std::cerr << "Failed to open the CSV file." << std::endl;
return 1;
}
std::vector<std::vector<std::string>> data; // 用于存储CSV数据的向量
std::string line;
while (std::getline(file, line)) {//循环读取行,每次存入到line
std::vector<std::string> row; //存储行的向量
std::string cell; //存储单元格的字符串变量
std::istringstream lineStream(line);//将字符串作为输入流进行处理
while (std::getline(lineStream, cell, ',')) {//以逗号分割,循环读取,每次存储到cell
row.push_back(cell);//把单元格字符串添加到行数组中
}
data.push_back(row);//把行数组添加到data数组中
}
// 打印读取的CSV数据
for(const auto& row:data){
for(const auto& cell:row){
std::cout << cell << " | ";
}
std::cout << std::endl;
}
return 0;
}
包装成函数
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <sstream>
// 定义一个类型别名,用于表示 CSV 数据(二维字符串向量)
using CSVData = std::vector<std::vector<std::string>>;
CSVData readCSV(const std::string& filename) {
CSVData data; // 存储 CSV 数据的二维向量
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Could not open file." << std::endl;
return data;
}
std::string line;
while (std::getline(file, line)) {//循环读取行,每次存入到line
std::vector<std::string> row; //存储行的向量
std::string cell; //存储单元格的字符串变量
std::istringstream lineStream(line);//将字符串作为输入流进行处理
while (std::getline(lineStream, cell, ',')) {//以逗号分割,循环读取,每次存储到cell
row.push_back(cell);//把单元格字符串添加到行数组中
}
data.push_back(row);//把行数组添加到data数组中
}
// file.close(); 与C语言不同,C++的std::ifstream类在退出作用域时会自动析构,可以不用手动关闭。
return data;
}
int main() {
CSVData csvData = readCSV("./test_data/rb2401_tick.csv");
// 打印读取的CSV数据
for(const auto& row:csvData){
for(const auto& cell:row){
std::cout << cell << " | ";
}
std::cout << std::endl;
}
return 0;
}
如果读取的csv文件很大,函数返回的是数据的副本,会影响效率,可以考虑改成移动语义。
函数返回用移动语义
using CSVData = std::vector<std::vector<std::string>>;
CSVData readCSV(const std::string& filename) {
CSVData data;
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "Error: Could not open file." << std::endl;
return data;
}
std::string line;
while (std::getline(file, line)) {
std::vector<std::string> row;
std::string cell;
std::istringstream lineStream(line);
while (std::getline(lineStream, cell, ',')) {
row.push_back(cell);
}
data.push_back(std::move(row)); // 使用 std::move 来避免复制
}
return std::move(data); // 使用 std::move 来避免复制
}
测试csv文件大小为32M
python的pandas读取并赋值给df用时才500多毫秒。
C++却要700多毫秒,改成移动语义也要600多毫秒。
可以考虑使用更高效的CSV解析库:C++社区中有许多针对CSV文件解析的高性能库,例如Fast-cpp-csv-parser。
或者用C语言来写这部分代码。