STL common algorithms


summary:

  • The algorithm is mainly composed of header files < algorithm < functional > < numeric >, which are non member functions
  • < algorithm > is the largest of all STL header files, covering comparison, exchange, search, traversal, copy, modification, etc
  • < numeric > is very small and only includes a few template functions that perform simple mathematical operations on the sequence
  • < functional > defines some template classes to declare function objects

1 common traversal algorithms

  • for_each / / traverse the container
  • transform / / transfer container to another container

1.1 for_each

Function prototype:

  • for_each(iterator begin, iterator end, func);
    Parameter interpretation:
    //The traversal algorithm traverses the container elements
    //beg start iterator
    //End end iterator
    // _ func function or function object
//Ordinary function
void printInt(int val)
{
	cout << val << " ";
}
//functor 
class print02
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test01()
{
	vector<int>v;
	for (int i=0; i<10; i++)
	{
		v.push_back(i);
	}
	for_each(v.begin(), v.end(), printInt)	//👀  Ordinary functions only need to put the function name
	cout << endl;
	for_each(v.begin(), v.end(), print02())	//👀  Imitation function, need to put function object
	cout << endl;
}

1.2 transform

Transport container to another container
Function prototype:

  • transform(iterator begi, iterator end1, iterator beg2, _func);
    Parameter interpretation:
    //beg1 source container start iterator
    //end1 source container end iterator
    //beg2 target container start iterator
    // _ func function or function object
class Transform
{
public:
	int operator()(int v)
	{
		return v;
	}
};
void test01()
{
	vector<int>v;
	for (int i=0; i<10; i++)
	{
		v.push_back(i);
	}
	vector<int>vTarget;
	vTarget.resize(v.size());	//👀  The target container needs to open up space in advance
	transform(v.begin(), v.end(), vTarget.begin(), Transform())	//👀  Imitation function, need to put function object
	cout << endl;
}

2 common search algorithms

  • Find / / find elements
  • find_if / / find elements by criteria
  • adjacent_find / / find adjacent duplicate elements
  • binary_search / / binary search
  • Count / / count the number of elements
  • count_if / / count the number of elements by condition

2.1 find

Function prototype:

  • find(iterator begin, iterator end, value);
    //Note: find the element by value, find and return the iterator at the specified position, and if not, return the end iterator position

Example: finding custom data types

class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age
	}
	// 👀  Overload = = the underlying find knows how to compare the person data type
	bool operator==(const Person& p)
	{
		if(this->m_Name == p.m_Name && this->m_Age == p.m_Age)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	string m_Name;
	int m_Age;
};

void test02()
{
	vector<Person> v;
	Person p1("aaa", 10);
	Person p2("bbb", 20);
	Person p3("ccc", 30);
	Person p4("ddd", 40);
	
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);

	Person pp("bbb", 20);
	vector<Person>::iterator it = find(v.begin(), v.end(), pp);
	if (it==v.end())
	{	
		cout << "Can't find" << endl;
	}
	else {cout << "Find element" << endl;}
}

2.2 find_if

Function prototype:

  • find_if(iterator begin, iterator end, _Pred);
    //Note: find the element by value, find and return the iterator at the specified position, and if not, return the end iterator position
    // _ Pred function or predicate (returns an imitation function of bool type)

1. Find built-in data types

class GreaterFive
{
public:
	bool operator()(int val)
	{
		return val > 5;
	}
};

void test01()
{
	vector<int> v;
	for (int i=0; i<10; i++)
	{
		v.push_back(i);
	}
	
	vector<int>::iterator it = find_if(v.begin(), v.end(), GreaterFive());
	if (it==v.end())
	{	
		cout << "Can't find" << endl;
	}
	else 
	{cout << "Find element" << endl;}
}

2.3 adjacent_find

Find adjacent, duplicate elements

Function prototype:

  • adjacent_find(iterator begin, iterator end);
    //Note: find the adjacent repeating element, find the first position iterator that returns the adjacent element, and if not, return the end iterator position

2.4 binary_search

Function prototype:

  • bool binary_search(iterator begin, iterator end, value);
    //Note: find elements by value, return true if found, and false if not found
    //Can only be used in ordered sequences

2.5 count

Number of statistical elements

Function prototype:

  • count(iterator begin, iterator end, value);
    //begin start iterator
    //End end iterator
    //Element of value statistics
    //Returns an int data

Example: Statistics custom data type

class Person
{
public:
	Person(string name, int age)
	{
		this->m_Name = name;
		this->m_Age = age;
	}
	bool operator ==(const Person& p)
	{
		if (this->m_Age == p.m_Age)
		{
			return true;
		}else
		{
			return false;
		}
	}
	string m_Name;
	int m_Age;
};

void test02()
{
	vector<Person> v;
	Person p1("Liu Bei", 35);
	Person p2("Guan Yu", 35);
	Person p3("Fei Zhang", 35);
	Person p4("Zhao Yun", 30);
	Person p5("Cao Cao", 40);
	v.push_back(p1);
	v.push_back(p2);
	v.push_back(p3);
	v.push_back(p4);
	v.push_back(p5);
	
	Person p("Zhuge Liang", 35)
	int num = count(v.begin(), v.end(), p);
	cout << "The number of people of the same age as Zhuge Liang is:" << num << endl;
}

2.6 cont_if

Count the number of elements by condition

Function prototype:

  • count_if(iterator begin, iterator end, _Pred);
    //begin start iterator
    //End end iterator
    // _ Perd predicate
    //Returns an int data

Example: Statistics built-in data type

class Greater20
{
pulic:
	bool operator()(int val)
	{
		return val > 20;
	}
};

void test01()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(40);
	v.push_back(30);
	v.push_back(20);
	v.push_back(40);
	
	int num = count_if(v.begin(), v.end(), Greater20());
	cout << "The number of elements greater than 20 is:" << num << endl;
}

3 common sorting algorithms

  • Sort / / sort the elements in the container
  • random_shuffle / / shuffle the elements within the specified range to randomly adjust the order
  • Merge / / merge container elements and store them in another container
  • reverse / / reverses the elements of the specified range

3.1 sort

Function prototype:

  • sort(iterator begin, iterator end, _Pred);
    //Find the element by value, find the iterator that returns the specified position, and the iterator that returns the end position cannot be found
    // _ Pred predicate. If it is not filled in, it is in ascending order by default
    Example:
void myPrint(int val)
{
	cout << val << " ";
}

void test01()
{
	vector<int> v;

	v.push_back(10);
	v.push_back(20);
	v.push_back(30);
	v.push_back(50);
	v.push_back(40);
	
	// Ascending by sort
	sort(v.begin(), v.end())
	for_each(v.begin(), v.end(), myPrint);
	cout << endl;
	// Change to descending order
	sort(v.begin(), b.end(), greater<int>());
	for_each(v.begin(), v.end(), myPrint);
	cout << endl;
}

3.2 random_shuffle

Function prototype:

  • random_shuffle(iterator begin, iterator end);
    //Randomly adjust the order of elements within the specified range

3.3 merge

Function prototype:

  • merge(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator dest
    //The container elements are merged and stored in the target container
    //Note: the two containers must be ordered
    //dest target container starts iterator (still ordered)

Example:

void test01()
{
	vector<int> v1;
	vector<int> v2;
	for (int i=0; i<10; i++)
	{
		v1.push_back(i);
		v2.push_back(i+1);
	}

	vector<int>vTarget;
	vTarget.resize(v1.size()+v2.size());
	merge(v1.begin(), v1.end(), v2.begin(), v2.end(), vTarget.begin());
}

3.4 reverse

Function prototype:

  • reverse(iterator begin, iterator end);
    //Inverts the elements of the specified range

4 common copy and replacement algorithms

  • Copy / / copy the elements of the specified range in the container to another container
  • replace / / modify the old element in the specified range in the container to a new element
  • replace_if / / replace the qualified element in the specified range in the container with a new element
  • Swap / / swap elements of two containers

4.1 copy

Function prototype:

  • copy(iterator begin, iterator end, iterator dest);
    //dest target start iterator

4.2 replace

Function prototype:

  • replace(iterator begin, iterator end, oldvalue, newvalue);
    //Replace the old element in the interval with a new element

4.3 replace_if

Function prototype:

  • replace_if(iterator begin, iterator end, _Pred, newvalue);
    //Replace the qualified elements in the interval with new elements

Example:

class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
class Greater30
{
public:
	bool Greater(int val)
	{
		return val >= 30;
	}
}

void test01()
{
	vector<int> v;
	v.push_back(10);
	v.push_back(40);
	v.push_back(20);
	v.push_back(30);
	
	cout << "Before replacement:" << endl;
	for_each(v.begin(), v.end(), MyPrint());
	//Replace 30 or more with 3000
	replace_if(v.begin(), v.end(), Greater30(), 3000);
}

4.4 swap

Function prototype:

  • swap(container c1, container c2);
    //Swap elements of two containers

Example:

class MyPrint
{
public:
	void operator()(int val)
	{
		cout << val << " ";
	}
};
void test01()
{
	vector<int> v1;
	vector<int> v2;
		
	for (int i=0; i<10, i++)
	{
		v1.push_back(i);
		v2.push_back(i+100);
	}
	cout << "Before replacement:" << endl;
	for_each(v1.begin(), v1.end(), MyPrint());
	for_each(v2.begin(), v2.end(), MyPrint());

	swap(v1, v2);
}

5 common arithmetic generation algorithms

The arithmetic production algorithm book belongs to a small algorithm and contains the header file #include < numeric > when used

  • Calculate / / calculate the cumulative sum of container elements
  • fill / / add element to container

5.1 accumulate

Function prototype:

  • accumulate(iterator begin, iterator end, value);
    //Calculate cumulative sum of container elements
    //Value starting value (equivalent to one)
void test01()
{
	vector<int> v;
	for (int i=0; i<100, i++)
	{
		v.push_back(i);
	}

	int total = accumulate(v.begin(), v.end(), 100);
}

5.2 fill

Function prototype:

  • fill(iterator begin, iterator end, value);
    //Calculate cumulative sum of container elements
    //Value padded value
void test01()
{
	vector<int> v;
	v.resize(10);

	fill(v.begin(), v.end(), 100);
}

6 common set algorithms

  • set_intersectoin(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator dest)
    //Find the intersection of two containers
    //Note: the two sets must be an ordered sequence
    //The obtained target container is also an ordered sequence
  • set_union(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator des)
    //Find the union of two containers
    //Note: the two sets must be an ordered sequence
  • set_difference(iterator begin1, iterator end1, iterator begin2, iterator end2, iterator des)
    //Find the difference set of two containers
    //Note: the two sets must be an ordered sequence
    //Container 1 and container 2 have sequential positions. Different parameter positions have different results

Keywords: C++ data structure Container

Added by screamer141 on Tue, 30 Nov 2021 14:53:09 +0200