常用遍历算法
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
struct MyPlus {
int operator()(int val) {
return val;
}
};
void MyPrint(int val) {
cout << val << " ";
}
void TransformTest() {
vector<int> v1, v2;
v2.resize(v1.size());
for (int i = 0; i < 10; i++) {
v1.push_back(i);
}
transform(v1.begin(), v1.end(), v2.begin(), MyPlus());
for_each(v2.begin(), v2.end(), MyPrint);
cout << endl;
}
int main() {
TransformTest();
return 0;
}
常用查找算法
void FindTest() {
vector<int> v1;
for (int i = 0; i < 10; i++) {
v1.push_back(i);
}
vector<int>::iterator it = find(v1.begin(), v1.end(), 5);
if (it != v1.end()) {
cout << "容器中存在:" << (*it) << endl;
}
else {
cout << "容器中找不到指定元素" << endl;
}
}
class Person {
public:
int mAge;
int mId;
Person(int age, int id) :mAge(age), mId(id) {}
bool operator==(Person p) {
return p.mId == this->mId && p.mAge == this->mAge;
}
};
void FindTest2(){
vector<Person> v;
Person p1(10, 20), p2(20, 30);
v.push_back(p1);
v.push_back(p2);
vector<Person>::iterator it = find(v.begin(), v.end(), p1);
if (it != v.end()) {
cout << "容器中存在" << endl;
}
else {
cout << "容器中找不到指定元素" << endl;
}
}
bool MySearch(int val) {
return val > 6;
}
bool MySearch2(int val) {
return val > 5;
}
void BinarySearchTest() {
vector<int> v1;
for (int i = 0; i < 10; i++) {
v1.push_back(i);
}
v1.push_back(9);
bool ret=binary_search(v1.begin(), v1.end(), 5);
if (ret) {
cout << "找到了" << endl;
}
else {
cout << "没有找到" << endl;
}
vector<int>::iterator it=adjacent_find(v1.begin(), v1.end());
if (it != v1.end()) {
cout << "找到了重复相邻元素:" <<(*it)<< endl;
}
else {
cout << "没找到重复相邻元素" << endl;
}
it = find_if(v1.begin(), v1.end(), MySearch);
if (it != v1.end()) {
cout << "找到了大于6的元素:" << (*it) << endl;
}
else {
cout << "没找到大于6的元素" << endl;
}
int num = count(v1.begin(), v1.end(), 9);
cout << "9出现的次数:" << num << endl;
num = count_if(v1.begin(), v1.end(), MySearch2);
cout << "大于5的数有:" << num << "个";
}