STL18常用算法
#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(); }總結
- 上一篇: STL2-类模板
- 下一篇: STL9-vector容器