一、vector
- 找到vector中的某个元素。vector是没有find函数的,但是可以借助algorithm头文件中的find函数来实现这一功能。如果需要查找的元素是一个结构体,可以在结构体中重载“==”
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
struct Point {
int x;
int y;
bool operator == (const Point& p) { //重载运算符,以比较复杂结构体
return (this->x == p.x) && (this->y == p.y);
}
};
vector<Point> points;
bool findPoint(int x, int y) {
Point p = { x,y };
vector<Point>::iterator it = find(points.begin(), points.end(),p);
if (it != points.end()) {
return true;
}
else {
return false;
}
}
- 对vector中的元素进行排序
借助于algorithm头文件中的sort函数,并可以自定义排序方法
#include<vector>
#include<algorithm>
using namespace std;
struct Point {
int id;
int distance;
};
vector<Point> points;
int x[200], y[200];
//排序方法
bool cmp(const Point& p1, const Point& p2) {
if (p1.distance == p2.distance) {
return p1.id < p2.id;
}
return p1.distance < p2.distance;
}
//排序
sort(points.begin(), points.end(), cmp);
二、输出格式
保留n位小数
#include<iomanip>
#include<iostream>
using namespace std;
cout<<fixed<<setprecision(n) << mid;
三、pair
pair<int, int> p = make_pair(2, 3);
cout << p.first << p.second << endl;