gpt4 book ai didi

c++ - 读取文件c++的最快方法

转载 作者:行者123 更新时间:2023-11-27 23:40:20 24 4
gpt4 key购买 nike

我想读入这样的文件:

13.3027 29.2191 2.39999
13.3606 29.1612 2.39999
13.3586 29.0953 2.46377
13.4192 29.106 2.37817

它有超过 1mio 行。

我当前的 cpp 代码是:

loadCloud(const string &filename, PointCloud<PointXYZ> &cloud)
{
print_info("\nLoad the Cloud .... (this takes some time!!!) \n");
ifstream fs;
fs.open(filename.c_str(), ios::binary);
if (!fs.is_open() || fs.fail())
{
PCL_ERROR(" Could not open file '%s'! Error : %s\n", filename.c_str(), strerror(errno));
fs.close();
return (false);
}

string line;
vector<string> st;

while (!fs.eof())
{
getline(fs, line);
// Ignore empty lines
if (line == "")
{
std::cout << " this line is empty...." << std::endl;
continue;
}

// Tokenize the line
boost::trim(line);
boost::split(st, line, boost::is_any_of("\t\r "), boost::token_compress_on);

cloud.push_back(PointXYZ(float(atof(st[0].c_str())), float(atof(st[1].c_str())), float(atof(st[2].c_str()))));
}
fs.close();
std::cout<<" Size of loaded cloud: " << cloud.size()<<" points" << std::endl;
cloud.width = uint32_t(cloud.size()); cloud.height = 1; cloud.is_dense = true;
return (true);
}

目前读取这个文件需要很长时间。我想加快这个速度,有什么想法该怎么做吗?

最佳答案

只要数字始终以三个为一组出现,您就可以只读取数字而不是整行加上解析。

void readFile(const std::string& fileName)
{
std::ifstream infile(fileName);

float vertex[3];
int coordinateCounter = 0;

while (infile >> vertex[coordinateCounter])
{
coordinateCounter++;
if (coordinateCounter == 3)
{
cloud.push_back(PointXYZ(vertex[0], vertex[1], vertex[2]));
coordinateCounter = 0;
}
}
}

关于c++ - 读取文件c++的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626056/

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