vector、set、map容器
vector和set的声明和遍历
vector的嵌套,大vector中嵌套多个小vector
#include
#include
using namespace std;
void test1() {
vector > vec;
vector v1;
vector v2;
vector v3;
for (int i = 0; i < 4; i++) {
v1.push_back(i + 1);
v2.push_back(i + 2);
v3.push_back(i + 3);
}
vec.push_back(v1); // 将三个vector容器放入一个大vector容器中
vec.push_back(v2);
vec.push_back(v3);
// 遍历嵌套容器
// for (vector >::iterator it = vec.begin(); it < vec.end(); it++) {
// for (vector::iterator vit = (*it).begin(); vit < (*it).end(); vit++) { // *it只解引用出的小容器
// cout << (*vit) << " ";
// }
// cout << endl;
// }
// 使用auto也可实现遍历
for (auto it = vec.begin(); it < vec.end(); it++) {
for (auto vit = (*it).begin(); vit < (*it).end(); vit++) { // *it只解引用出的小容器
cout << (*vit) << " ";
}
cout << endl;
}
}
int main() {
test1();
return 0;
}
map的声明和遍历
#include
#include
#include
map仿函数(函数对象)
当给对象排序时,必须使用仿函数(即类)
bool operator()(int k1, int k2) const { // 仅根据key排序 return k1 > k2; }
#include
#include
函数对象的三种使用方式
#include
using namespace std;
class MyAdd {
public:
int operator()(int a, int b) {
return a + b;
}
};
class MyPrint {
public:
int count;
MyPrint() {
this->count = 0;
}
void operator()(string text) {
// this->count++; // 阔以~
count++;
cout << text << endl;
}
};
void test1() {
MyAdd myAdd;
int ret = myAdd(1, 2);
cout << "ret:" << ret << endl;
}
void test2() {
MyPrint myPrint;
myPrint("lwt1");
myPrint("lwt2");
myPrint("lwt3");
cout << "调用仿函数的次数:" << myPrint.count << endl;
}
void doPrint(MyPrint &mp,string text){
mp(text);
}
void test3(){
MyPrint myPrint;
doPrint(myPrint,"void doPrint(MyPrint &mp,string text) lwt666");
}
int main() {
test1();
test2();
test3();
return 0;
}