@2020某比賽學到的知識總結
1# 如何讀取txt文件中的數據
txt文件內的數據如下所示,每一行代表一個轉賬記錄,第一列和第二列是ID,
158,295,638
295,175,594
175,158,273
23,179,329
179,121,636
121,23,309
128,231,631
231,64,627
將txt裏面的每一個值讀取出來,並當作int變量
string testFile = "/data/test_data.txt";//文件絕對路徑和名稱
FILE* file=fopen(testFile.c_str(),"r");//打開文件,”r“代表讀權限
int u,v,c;
int cnt=0;
while(fscanf(file,"%d,%d,%d",&u,&v,&c)!=EOF){
//EOF代表結束標誌,fscanf代表逐行讀取,u是第一個數字
inputs.push_back(u);
inputs.push_back(v);
++cnt;
}
## 將數據寫入文件
將數組內的元素一個一個寫入文件
//O_RDWR是讀寫,O_CREAT,表示沒有文件的話創建文件,0666代表權限
open("/projects/student/result.txt", O_RDWR | O_CREAT,0666);
ofstream out(outputFile);//表示向文件內寫入數據
out<<circles.size()<<endl;//通過out向文件內寫入數據
for(auto &x:circles){//
auto path=x.path;
int sz=path.size();
out<<path[0];
for(int i=1;i<sz;i++)
out<<","<<path[i];
out<<endl;
}
##數據結構unordered_map<>
數據結構 unordered_map<ui,int>, 可以實現映射功能,可以快速查找元素,類似於哈希表
例如:
vector<ui>temp;
//temp裏面是ui類型的ID值
for(ui &x:temp){
idHash[x]=nodeCnt++;//將ID(x)映射到0,1,2,3....也就是它在temp數組內的位置
// //然後通過temp[i]便可以找到 x
}
##數據結構vector
現在大家都用vector來創建數組
如
vector<Path> circles;
vector<vector<int>> Scc;
vector<vector<int>> A;
vector<int>B;
//以上創建都沒有開闢空間
vector<int> C(5,0);//直接開闢空間,並且設置初值
//C={0,0,0,0,0}
//vector在末尾添加元素
A.push_back(B)
//vector刪除末尾元素
A,pop_back();
//對vector排序,默認升序
sort(B.begin(),B.end());
//刪除vector內的元素
B.erase(B.begin(),B.begin()+i)//將B[i]前的元素都刪掉
B.erase(B.begin())//刪除B的首元素
//刪除vector內重複的元素,這時必須保證vector是有序的
temp.erase(unique(temp.begin(),temp.end()),temp.end());
//vector插入元素
B.insert(B.begin()+i,3);//將3,插入到第i個位置也就是B[i]=3
#運算符重載:
對於結構體來說,我們來比較兩個結構體對象式時,就要在結構體內重載運算符,不然就會出粗
struct Path{
int length;
vector<ui> path;
Path(int length, const vector<ui> &path) : length(length), path(path) {}
bool operator<(const Path&rhs)const{//重載”<“運算符
if(length!=rhs.length) return length<rhs.length;
for(int i=0;i<length;i++){
if(path[i]!=rhs.path[i])
return path[i]<rhs.path[i];
}
}
bool operator==(const Path&rhs)const{//重載”=“運算符
if(this->length!=rhs.length) return false;
for(int i=0;i<this->length;i++){
if(this->path[i]!=rhs.path[i])
return false;
}
return true;
}
};