C++ set/multiset container (associative container)

1. Basic concepts

 Include the header file: #include <set> //set is the same as multiset

 Sort automatically!

PS For custom data types, specify the collation (using functors)

2. Constructor

 

3. Size and exchange

Sets cannot be resized.

 4. Insertion and deletion

 Data cannot be inserted at the specified position, because the set will be sorted by default.

5. Find and count

6. The difference between set and multiset

 

7. Create a pair

 

	pair<string, int> p1 = make_pair("Jerry", 20);
	pair<string, int> p2("Jerry", 20);
	cout << "name: " << p1.first << " age: " << p1.second << endl;

8. Set container sorting

Use the functor to modify the collation of the set.

A functor, also known as a function object (Function Object), is a class that can perform function functions.

A functor is a class that defines a member function with operator(), which can be regarded as a general function, except that the function of this function is implemented in the operator operator() in a class, and it is a function object that converts the function Used as a way to pass parameters. Calling the functor is actually calling the overloaded operator() operator through the class object.

Advantages and disadvantages of functors:

Advantages:
1) The execution speed of the functor is faster than that of the function pointer. The function pointer is called through the address, and the functor is to customize the operator to improve the efficiency of the call.
2) A functor is more flexible than a general function, and can have two different state entities at the same time, which a general function does not have.
3) Functors can be used as template parameters because each functor has its own type.
Disadvantages:
1) A class needs to be implemented separately.
2) The definition form is more complicated.


Functions of the functor:
1) As a sorting rule , in some special cases when the operator < or > cannot be directly used for sorting, the functor can be used.
2) Used as a discriminant , that is, the return value is bool type.
3) Have multiple internal states at the same time, such as returning a value and accumulating at the same time.
4) Used as the return value of the algorithm for_each

Example: Functors used as collations

class KCompare   //仿函数指定排序规则
{
public:
	bool operator()(int v1, int v2) //重载()运算符
	{
		return v1 > v2;
	}

};


void test05()
{
	set<int, KCompare> s1;
	s1.insert(10);
	s1.insert(70);
	s1.insert(50);
	s1.insert(20);
	s1.insert(30);
	s1.insert(200);

	for (set<int, KCompare>:: iterator it = s1.begin(); it != s1.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;

}

Guess you like

Origin blog.csdn.net/MWooooo/article/details/126706159