C ++ Standard Template Library Common Algorithm Usage Overview

Many algorithms are provided in algorithm, but when there are container member functions and global functions (algorithms) at the same time, priority is given to using member functions with the same name. If there are no member functions with the same name, these algorithms are considered

1.for_each (traversal)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

void myfunc(int c)
{
	cout << c << endl;
}

class A
{
public:
	void operator()(int c)
	{
		cout << c << endl;
	}
};
int main()
{
	vector<int> vec = { 5,4,3,1,2 };

	//第一种调用方法,第三个参数传入一个函数
	for_each(vec.begin(), vec.end(), myfunc);


	//第二种调用方法,第三个参数传入一个仿函数
	for_each(vec.begin(), vec.end(), A());

	//第三种调用方法,第三个参数传入一个lambda表达式
	for_each(vec.begin(), vec.end(), [](int c) { cout<<c<<endl; });

	return 0;
}

Reference blog: C ++ imitation function    C ++ lambda expression

2 find

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
	vector<int> vec = { 5,4,3,1,2 };

	vector<int>::iterator finditer = find(vec.begin(), vec.end(), 400); //判断是否等于find的第二个参数,等于就没找到,不等于就找到了
	
	if (finditer != vec.end())
	{
		cout << "找到了" << endl;
	}
	else
	{
		cout << "没找到" << endl;
	}

	return 0;
}

3 find_if

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
	vector<int> vec = { 5,4,3,1,2 };

	vector<int>::iterator finditer = find_if(vec.begin(), vec.end(), [](int c)
	{
		if (c < 3)
			return true;
		return false;
	}); 
	
	if (finditer != vec.end())
	{
		cout << "找到了:" <<*finditer<< endl;
	}
	else
	{
		cout << "没找到" << endl;
	}

	return 0;
}

4 sort (only supports containers containing random access iterators, such as vector)

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


bool myfunc(int i, int j)
{
	if (i < j)
		return true;
	return false;
}

int main()
{
	vector<int> vec = { 5,4,3,1,2 };
	sort(vec.begin(), vec.end(), myfunc);

	for_each(vec.begin(), vec.end(), [](int c) {cout << c << endl; });

	return 0;
}

 

5 Supplement

Many algorithms are provided in algorithm, but when there are container member functions and global functions (algorithms) at the same time, priority is given to using member functions with the same name. If there are no member functions with the same name, these algorithms are considered

Published 123 original articles · praised 31 · 90,000 views +

Guess you like

Origin blog.csdn.net/qq_40794602/article/details/103082621