vector预分配问题
读取运算十几万行几列的数据文件运算并输出,但是速度非常慢,得好几分钟vector有缺陷,但是是不是预分配空间就可以,但是不知道vector < vector > vec;怎么分配,好像没有效果!求助!
cpp
#include <fstream> #include <iostream> #include <string> #include <sstream> #include <vector> using namespace std; #define pi 3.141592653 int main() { ifstream readfile; ofstream outfile; string file_name; string file_name2; string sline; float data; int n; int m; int i; int j; vector <float> v; vector < vector <float> > vec; double a; double b; a = 0.005*pi/180; b = 0.005; cout << "输入文件名:"; cin >> file_name; vec.clear(); readfile.open((char *)file_name.c_str(), ios::in); i = 0; while(!readfile.eof()) { getline(readfile, sline); stringstream buf(sline); v.clear(); while(!buf.eof()) { //v.reserve(850000); buf >> data; v.push_back(data); } //vec.reserve(850000); vec.push_back(v); i++; } readfile.close(); cout << "输入文件名:"; cin >> file_name2; outfile.open((char *)file_name2.c_str(), ios::out); n = vec.size(); for(i=0;i<n;i++) { m = vec[i].size(); for(j=0;j<m;j++) { outfile<<vec[i][j] * (j==0?1:(j<4?a:b)); cout<<endl; if(j<m-1) outfile << char(0x20); } if(i<n-1) outfile << endl; } outfile.close(); return 0; }
片仓小次郎
9 years, 7 months ago