@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;
}
};