cpp ► STL container - > sort container - > set

Posted by Flames on Mon, 24 Jan 2022 12:05:29 +0100

describe

std::set
template <class T, class Compare = less<T>, class Alloc = allocator<T>> class set;
A set collection is a container that stores unique elements in a specific order.

In set, the value of the element also identifies it (the value itself is key and the type is T), and each value must be unique. The values of elements in set cannot be modified in the container (elements are always constants), but they can be inserted or deleted from the container.

Internally, elements in a set are always sorted according to a specific strict weak sorting criterion indicated by their internal comparison object (Compare type).

set containers are usually better than unordered_set containers are slow to access individual elements through key s, but they allow direct iteration of subsets based on their order.

The typical implementation of set is binary search tree.

Container properties
  • Associative
    The element in the associated container is referenced by its key, not by its absolute position in the container.
  • Ordered
    The elements in the container always follow a strict order. All inserted elements are given a position in this order.
  • Set
    The value of the element is also the key used to identify it.
  • Unique keys
    No two elements in a container can have an equivalent key.
  • Allocator-aware
    Containers use allocator objects to dynamically process their storage requirements.
Member types
Member typedefinitionremarks
key_typeFirst template parameter
value_typeFirst template parameter
key_compareSecond template parameter (Compare)The default is: less < key_ type>
value_compareSecond template parameter (Compare)The default is: less < value_ type>
Member functions

Constructor:

// constructing sets
#include <iostream>
#include <set>
bool fncomp(int lhs, int rhs) { 
	return lhs < rhs; 
}
struct classcomp {
	bool operator() (const int& lhs, const int& rhs) const {
		return lhs < rhs;
	}
};
int main() {
	std::set<int> first;// empty set of ints

	int myints[] = { 10,20,30,40,50 };
	std::set<int> second(myints, myints + 5);// range
	std::set<int> third(second);// a copy of second
	std::set<int> fourth(second.begin(), second.end());// iterator ctor.
	std::set<int, classcomp> fifth;// class as Compare

	bool(*fn_pt)(int, int) = fncomp;
	std::set<int, bool(*)(int, int)> sixth(fn_pt);// function pointer as Compare
	return 0;
}
Modifiers
  • emplace_hint
    template <class... Args> iterator emplace_hint(const_iterator position, Args&&... args);
    effect:
    Construct and insert elements with hints.
    return:
    If the element is successfully inserted, the function returns an iterator pointing to the newly inserted element.
    Otherwise, an iterator is returned pointing to the element in the container equal to the inserted element.
    The member type iterator is a bidirectional iterator that points to an element.
// set::emplace_hint
#include <iostream>
#include <set>
#include <string>
int main() {
	std::set<std::string> myset;
	auto it = myset.cbegin();

	myset.emplace_hint(it, "alpha");
	it = myset.emplace_hint(myset.cend(), "omega");
	it = myset.emplace_hint(it, "epsilon");
	it = myset.emplace_hint(it, "beta");

	std::cout << "myset contains:";
	for (const std::string& x : myset)
		std::cout << ' ' << x;
	return 0;
}
myset contains: alpha beta epsilon omega
Observers
  • key_comp/value_comp
    key_compare key_comp() const;
    value_compare value_comp() const;
    Returns the comparison object. By default, this is a less object, and its return is the same as operator <.
    The definition of less object is as follows:
template <class T> struct less {
	bool operator() (const T& x, const T& y) const {
		return x < y;
	}
	typedef T first_argument_type;
	typedef T second_argument_type;
	typedef bool result_type;
};
// set::key_comp
#include <iostream>
#include <set>
int main() {
	std::set<int> myset;
	int highest;
	std::set<int>::key_compare mycomp = myset.key_comp();
	/*Or STD:: set < int >:: value_ compare mycomp = myset. value_ comp(); */
	for (int i = 0; i <= 5; i++) 
		myset.insert(i);
	std::cout << "myset contains:";
	highest = *myset.rbegin();
	std::set<int>::iterator it = myset.begin();
	do {
		std::cout << ' ' << *it;
	} while (mycomp(*(++it), highest));
	return 0;
}
myset contains: 0 1 2 3 4
Operations
  • find
    iterator find(const value_type& value) const;
    Search for an element equivalent to val in the container. If it is found, it returns the iterator. Otherwise, it returns the iterator set::end.
    If the container's comparison object reflexively returns false (that is, regardless of the order in which the elements are passed as parameters), the two elements in the collection are considered equivalent.
// set::find
#include <iostream>
#include <set>
int main(){
    std::set<int> myset;
    std::set<int>::iterator it;
    // set some initial values:
    for (int i = 1; i <= 5; i++) 
        myset.insert(i * 10);// set: 10 20 30 40 50
    it = myset.find(20);
    myset.erase(it);
    myset.erase(myset.find(40));
    std::cout << "myset contains:";
    for (it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    return 0;
}
myset contains: 10 30 50
  • count
    size_type count(const value_type& val) const;
    Counts elements with specific values.
    Because all elements are unique in the set container, the function can only return 0 or 1.
// set::count
#include <iostream>
#include <set>
int main() {
	std::set<int> myset;
	// set some initial values:
	for (int i = 1; i < 5; ++i)
		myset.insert(i * 3);// set: 3 6 9 12

	for (int i = 0; i < 10; ++i) {
		std::cout << i;
		if (myset.count(i) != 0)
			std::cout << " is an element of myset.\n";
		else
			std::cout << " is not an element of myset.\n";
	}
	return 0;
}
0 is not an element of myset.
1 is not an element of myset.
2 is not an element of myset.
3 is an element of myset.
4 is not an element of myset.
5 is not an element of myset.
6 is an element of myset.
7 is not an element of myset.
8 is not an element of myset.
9 is an element of myset.
  • lower_bound,upper_bound
    iterator lower_bound(const value_type& val) const;
    Returns an iterator that points to the first element equal to or after val.
    iterator upper_bound(const value_type& val) const;
    Returns an iterator that points to the first element after val.
// set::lower_bound/upper_bound
#include <iostream>
#include <set>
int main() {
    std::set<int> myset;
    std::set<int>::iterator itlow, itup;

    for (int i = 1; i < 10; i++) 
        myset.insert(i * 10);// 10 20 30 40 50 60 70 80 90

    itlow = myset.lower_bound(30);// *itlow==30
    itup = myset.upper_bound(60);// *itup==70

    myset.erase(itlow, itup);// 10 20 70 80 90

    std::cout << "myset contains:";
    for (std::set<int>::iterator it = myset.begin(); it != myset.end(); ++it)
        std::cout << ' ' << *it;
    return 0;
}
myset contains: 10 20 70 80 90
  • equal_range
    pair<iterator, iterator> equal_range(const value_type& val) const;
    Returns the boundary of the range containing all elements in the container equivalent to val.
    Because all elements in the collection container are unique, the returned range contains at most one element.
    The function returns a pair whose member pair::first is the lower limit of the range (the same as lower_bound), and pair::second is the upper limit (the same as upper_bound).
// set::equal_elements
#include <iostream>
#include <set>
int main() {
	std::set<int> myset;
	for (int i = 1; i <= 5; i++) 
		myset.insert(i * 10);// myset: 10 20 30 40 50

	std::pair<std::set<int>::const_iterator, std::set<int>::const_iterator> ret;
	ret = myset.equal_range(30);

	std::cout << "the lower bound points to: " << *ret.first << '\n';
	std::cout << "the upper bound points to: " << *ret.second << '\n';
	return 0;
}
the lower bound points to: 30
the upper bound points to: 40

std::pair
template <class T1, class T2> struct pair;
This class couples a pair of values of different types (T1 and T2). A single value can be accessed through its public members (first and second).
Template parameter T1: type of member first, alias first_type.
Template parameter T2: type of member second, alias second_type.
Member variable: first -- the first value in pair; Second -- the second value in pair.

Topics: C++