[C++]STL-常用算法

常用遍历算法

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<vector>
#include<map>
#include<algorithm>
using namespace std;
//常用的遍历算法

//for_each算法与之前一致



//transform算法 将指定容器区间元素搬运至另一容器中
//注意:transform不会给目标容器分配内存,所以需要我们提前分配好内存

struct MyPlus {
	int operator()(int val) {
		return val;
	}
};

void MyPrint(int val) {
	cout << val << "  ";
}

void TransformTest() {
	vector<int> v1, v2;
	v2.resize(v1.size());
	//注意:这里想要往v2中传送元素,必须先给v2提供足够的内存空间
	//并且这里不可以用reverse,reverse提供的空间未初始化无法赋值
	for (int i = 0; i < 10; i++) {
		v1.push_back(i);
	}
	transform(v1.begin(), v1.end(), v2.begin(), MyPlus());  //向v2传输数据
	//MyPlus函数的返回值决定了向v2传输的数据
	for_each(v2.begin(), v2.end(), MyPrint);  
	cout << endl;

}




int main() {

	TransformTest();
	return 0;
}

常用查找算法


//find(iterator beg,iterator end,value)函数
//最常见的查找函数,在指定区间内查找指定元素


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;
	}
}

//binary_search  二分查找法

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;
	}

	//adjacent_find()查找重复相邻的元素,并返回迭代器
	vector<int>::iterator it=adjacent_find(v1.begin(), v1.end());
	if (it != v1.end()) {
		cout << "找到了重复相邻元素:" <<(*it)<< endl;
	}
	else {
		cout << "没找到重复相邻元素" << endl;
	}


	//find_if 会根据条件返回第一个满足条件的迭代器
	it = find_if(v1.begin(), v1.end(), MySearch);
	if (it != v1.end()) {
		cout << "找到了大于6的元素:" << (*it) << endl;
	}
	else {
		cout << "没找到大于6的元素" << endl;
	}


	//count()统计元素出现次数
	int num = count(v1.begin(), v1.end(), 9);
	cout << "9出现的次数:" << num << endl;

	//count_if  返回满足条件的元素的个数
	num = count_if(v1.begin(), v1.end(), MySearch2);
	cout << "大于5的数有:" << num << "个";

}
发布了18 篇原创文章 · 获赞 2 · 访问量 216

猜你喜欢

转载自blog.csdn.net/renboyu010214/article/details/104430294