vector、set、map容器
vector和set的声明和遍历
vector的嵌套,大vector中嵌套多个小vector
#include <iostream>
#include <vector>
using namespace std;
void test1() {
vector<vector<int> > vec;
vector<int> v1;
vector<int> v2;
vector<int> 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);
vec.push_back(v2);
vec.push_back(v3);
for (auto it = vec.begin(); it < vec.end(); it++) {
for (auto vit = (*it).begin(); vit < (*it).end(); vit++) {
cout << (*vit) << " ";
}
cout << endl;
}
}
int main() {
test1();
return 0;
}
map的声明和遍历
#include <iostream>
#include <set>
#include <map>
using namespace std;
void printMap(map<int, int> *map1) {
for (map<int, int>::iterator it = map1->begin(); it != map1->end(); it++) {
cout << "key:" << (*it).first << " value:" << (*it).second << endl;
}
}
int main() {
set<int> s;
s.insert(20);
s.insert(10);
s.insert(40);
s.insert(30);
pair<set<int>::iterator, bool> ret = s.insert(10);
if (ret.second) {
cout << "successful!" << endl;
return 0;
}
cout << "fail" << endl;
map<int, int> map1;
map1.insert(pair<int, int>(1, 666));
map1.insert(make_pair(2, 777));
map1.insert(make_pair(3, 888));
printf("------------\n");
printMap(&map1);
printf("------------\n");
map<int, int>::iterator pos = map1.find(1);
if (pos != map1.end()) {
cout << "key为" << pos->first << " value为" << pos->second << endl;
} else {
cout << "未找到该key对应的value" << endl;
}
printf("------------");
return 0;
}
map仿函数(函数对象)
当给对象排序时,必须使用仿函数(即类) bool operator()(int k1, int k2) const { // 仅根据key排序 return k1 > k2; }
#include <iostream>
#include <map>
using namespace std;
class MyCompare {
public:
bool operator()(int k1, int k2) const {
return k1 > k2;
}
};
int main() {
map<int, int, MyCompare> map2;
map2.insert(pair<int, int>(1, 666));
map2.insert(make_pair(2, 999));
map2.insert(make_pair(3, 888));
for (map<int, int, MyCompare>::iterator it = map2.begin(); it != map2.end(); it++) {
cout << "key:" << (*it).first << " value:" << (*it).second << endl;
}
return 0;
}
函数对象的三种使用方式
#include <iostream>
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) {
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;
}
|