64,636
社区成员
发帖
与我相关
我的任务
分享
int main()
{
ifstream ifs("..//pre.txt");
vector<vector<double>> data_all(128);
stringstream buffer;
buffer << ifs.rdbuf();
string contents = buffer.str();
string::size_type pos1 = 0, n = 0;
int i = 0;
while ((pos1 = contents.find_first_of("+-.0123456789e", pos1)) != string::npos)
{
auto pos2 = contents.find_first_not_of("+-.0123456789e", pos1);
n = pos2 - pos1;
double d = stod(contents.substr(pos1, n));
data_all[i].push_back(d);
pos1 += n;
if ((i != 127) && (contents[pos1] == '\n'))
++i;
}
}
int main()
{
//写个测试文件
//ofstream of("d:/1.txt");
//for (int i=0;i<128*3300;i++)
// of.write("5.8774718e-39 ",14);
//of.flush();
time_t start=clock();
const int row=128;
const int column=3300;
ifstream ifs("d:/1.txt");
stringstream buffer;
buffer<<ifs.rdbuf();
vector<vector<double>> data_all(row,vector<double>(column));
string tmp;
for (int i=0;i<row;i++)
for (int j=0;j<column;j++)
{
buffer>>tmp;
data_all[i][j]=stod(tmp);
}
time_t end=clock();
cout<<"the running time is : "<<double(end-start)/CLOCKS_PER_SEC<<endl;
return 0;
}
[/quote]
好的,非常感谢!int main()
{
//写个测试文件
//ofstream of("d:/1.txt");
//for (int i=0;i<128*3300;i++)
// of.write("5.8774718e-39 ",14);
//of.flush();
time_t start=clock();
const int row=128;
const int column=3300;
ifstream ifs("d:/1.txt");
stringstream buffer;
buffer<<ifs.rdbuf();
vector<vector<double>> data_all(row,vector<double>(column));
string tmp;
for (int i=0;i<row;i++)
for (int j=0;j<column;j++)
{
buffer>>tmp;
data_all[i][j]=stod(tmp);
}
time_t end=clock();
cout<<"the running time is : "<<double(end-start)/CLOCKS_PER_SEC<<endl;
return 0;
}
int main()
{
const int row=128;
const int column=3300;
ifstream ifs("..//pre.txt");
stringstream buffer;
buffer<<ifs.rdbuf();
vector<vector<double>> data_all(row,vector<double>(column));
for (int i=0;i<row;i++)
for (int j=0;j<column;j++)
buffer>>data_all[i][j];
return 0;
}
确实是没开优化...然后就是strtod是C标准库里的字符串转double函数,总觉着C和C++的函数混在一块用有点膈应...strtod可以将所有的字符串全部转换为double吗?不用将字符串分开是吗?感谢! 恒定列数不要用二维vector,自己写个二维容器或者用OpenCV的Mat。如果不是实在懒得不行不要挨个substr在stod,直接在原来的字符串里strtod。不过我还是赌你没开优化。
int main()
{
const int Column = 128;
const int Row = 4096;
std::ifstream ifs("D:\\2.txt");
std::istream_iterator<std::string> buffer(ifs);
std::vector<std::vector<double>> data_all(Row);
//std::cout << std::setprecision(8);
for (int i = 0; i < Row; ++i)
{
data_all[i].reserve(Column);
for (int j = 0; j < Column; ++j)
{
data_all[i].push_back(std::stod(*(buffer++)));
//std::cout << data_all[i].back() << " ";
//Sleep(500);
}
}
}
先为vector预分配足够大小的空间( reserve ),这样不会随着插入频繁重分配