#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
//transform 将一个容器中的元素搬运在另一个容器中
#if 0 //错误
struct PrintVector {void operator()(int v) {cout << v << " ";}
};
void test01() {vector<int> v1, v2;for (int i = 0; i < 10; i++){v1.push_back(i);}transform(v1.begin(), v1.end(), v2.begin(), PrintVector());
}
#endif
void MyPrint(int val) {cout << val << " ";
}
struct PrintVector {int operator()(int v) {return v+100;}
};
void test01() {vector<int> v1, v2;//v2.reserve(100); 错误/*v2.resize(100);*/for (int i = 0; i < 10; i++) {v1.push_back(i);}v2.resize(v1.size()); transform(v1.begin(), v1.end(), v2.begin(), PrintVector());for_each(v2.begin(), v2.end(), MyPrint);
}
int main() {test01();return 0;
}
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;void test01() {vector<int> v1;for (int i = 0; i < 10; i++) {v1.push_back(i);}vector<int>::iterator ret = find(v1.begin(), v1.end(), 5);if (ret != v1.end())cout <<"找到了"<< *ret << endl;
}class Person {
public:Person(int age, int id) :age(age), id(id) {}bool operator==(const Person &p) const{return p.id == this->id && p.age == this->age;}
public:int age;int id;
};
void test02() {Person p1(10, 100);Person p2(20, 200);Person p3(30, 300);Person p4(40, 400);vector<Person> vp;vp.push_back(p1);vp.push_back(p2);vp.push_back(p3);vp.push_back(p4);vector<Person>::iterator ret=find(vp.begin(), vp.end(), p1); if (ret != vp.end())cout << "找到了" << (*ret).age<< " "<<(*ret).id << endl;elsecout << "没有找到" << endl;}//binary_research 二分查找法
void test03() {vector<int> v1;for (int i = 0; i < 10; i++) {v1.push_back(i);}bool ret=binary_search(v1.begin(), v1.end(), 5);if (ret) {cout << "找到了" << endl;}elsecout << "没有找到" << endl;
}
bool MySearch(int val) {return val > 5;
}bool MyCount(int val) {return val > 5;
}
//adjacent_find 查找相邻重复位置
void test04() {vector<int> v1;for (int i = 0; i < 10; i++) {v1.push_back(i);}v1.push_back(2);sort(v1.begin(), v1.end());for (int i = 0; i < v1.size(); i++) {cout << v1[i] << " ";}cout << endl;vector<int>::iterator ret=adjacent_find(v1.begin(), v1.end());if (ret != v1.end()) {cout << "找到相邻重复元素" << endl;cout << *ret << endl;}else {cout << "没有找到相邻重复元素" << endl;}//find_if 会根据条件(函数) 返回第一个 满足条件的迭代器ret=find_if(v1.begin(), v1.end(), MySearch);if (ret != v1.end()) {cout << "找到大于5的数" << endl;cout << *ret << endl;}else {cout << "没有找到大于5的数" << endl;}//count count_ifint num=count(v1.begin(), v1.end(), 2);cout << "9出现的次数:" << num << endl;num=count_if(v1.begin(), v1.end(), MyCount);cout << "大于5的元素出现的个数:" << num << endl;
}
int main() {cout << "test01" << endl;test01();cout << endl << "test02" << endl;test02();cout << endl << "test03" << endl;test03();cout << endl << "test04" << endl;test04();
}