STL Standard Template Library Learning Notes 2 (STL sorting container)

Keywords: C++

Associative containers can quickly find, read or delete stored elements. At the same time, this type of container is more efficient than sequential containers in inserting elements.

The elements stored in associative containers are "key value pairs" (< key, value >), which is the biggest difference from sequential containers. In addition, the elements stored in sequential containers are not sorted by default, while the elements stored in associative containers are sorted in ascending order according to the size of the key value of each element by default.

Associative container namecharacteristic
mapDefined in the < Map > header file, the key of each element of the data stored in the container must be unique (i.e. cannot be repeated). The container will sort in ascending order by default according to the size of the key of each element (call STD:: less < T >).
setDefined in the < set > header file, using the data stored in the container, the keys and values of each element are identical, and the values of each element cannot be repeated (ensuring the uniqueness of each element key). The container will automatically sort in ascending order according to the size of each element's key (in fact, the element value) (call STD:: less < T >).
multimapDefined in the < Map > header file, the only difference from the map container is that the keys for storing elements in the multimap container can be repeated.
multisetDefined in the < set > header file, the only difference from the set container is that the values of the elements stored in the multiset container can be repeated (once the values are repeated, it means that the keys are also repeated).

pair type  

#include <iostream>
#include <utility>      // pair
#include <string>       // string
using namespace std;
int main() {
    // Call constructor 1, which is the default constructor
    pair <string, double> pair1;
    // Call the second constructor
    pair <string, string> pair2("STL course","http://c.biancheng.net/stl/");  
    // Call copy constructor
    pair <string, string> pair3(pair2);
    //Call the move constructor
    pair <string, string> pair4(make_pair("C++course", "http://c.biancheng.net/cplus/"));
    // Call the 5th constructor
    pair <string, string> pair5(string("Python course"), string("http://c.biancheng.net/python/"));  
   
    cout << "pair1: " << pair1.first << " " << pair1.second << endl;
    cout << "pair2: "<< pair2.first << " " << pair2.second << endl;
    cout << "pair3: " << pair3.first << " " << pair3.second << endl;
    cout << "pair4: " << pair4.first << " " << pair4.second << endl;
    cout << "pair5: " << pair5.first << " " << pair5.second << endl;
    return 0;
}

 pair1:  0
pair2: STL tutorial http://c.biancheng.net/stl/
pair3: STL tutorial http://c.biancheng.net/stl/
pair4: C + + tutorial http://c.biancheng.net/cplus/
pair5: Python tutorial http://c.biancheng.net/python/

just so so

pair1.first = "Java course";
pair1.second = "http://c.biancheng.net/java/";
cout << "new pair1: " << pair1.first << " " << pair1.second << endl;

pair <string, string> pair4 = make_pair("C++course", "http://c.biancheng.net/cplus/");
cout << "pair4: " << pair4.first << " " << pair4.second << endl;

In addition to providing methods for creating pair objects, the < utility > header file also overloads <, < =, >, > =, =, == The operation rule of these 6 operators is: for the two pair objects to be compared, first compare the size of pair.first element. If they are equal, continue to compare the size of pair.second element.

The pair class template also provides a swap() member function, which can exchange the key value pairs of two pair objects. The precondition for successful operation is that the key and value types of the two pair objects must be the same.

#include <iostream>
#include <utility>      // pair
#include <string>       // string
using namespace std;
int main() {
    pair <string, int> pair1("pair", 10);                   
    pair <string, int> pair2("pair2", 20);
    //Exchange the key value pairs of pair1 and pair2
    pair1.swap(pair2);
    cout << "pair1: " << pair1.first << " " << pair1.second << endl;
    cout << "pair2: " << pair2.first << " " << pair2.second << endl;
    return 0;
}

pair1: pair2 20
pair2: pair 10

map type

#include <iostream>
#include <map>      // map
#include <string>       // string
using namespace std;
int main() {
    //Create an empty map container. By default, key value pairs are sorted in descending order according to the value of the middle key of a key value pair
    std::map<std::string, std::string, std::greater<std::string>>myMap;

    //equivalence
    std::map<std::string, int>myMap{ {"C Language course",10},{"STL course",20} };
    std::map<std::string, int, std::less<std::string> >myMap{ {"C Language course",10},{"STL course",20} };

    //Call the empty () method to construct a new key value pair directly to the specified location in the myMap container
    myMap.emplace("C Language course","http://c.biancheng.net/c/");
    myMap.emplace("Python course", "http://c.biancheng.net/python/");
    myMap.emplace("STL course", "http://c.biancheng.net/stl/");
    //Output the number of key value pairs stored in the current myMap container
    cout << "myMap size==" << myMap.size() << endl;
    //Judge whether the current myMap container is empty
    if (!myMap.empty()) {
        //With the help of the myMap container iterator, the key value pairs of the container are output one by one
        for (auto i = myMap.begin(); i != myMap.end(); ++i) {
            cout << i->first << " " << i->second << endl;
        }
    }  
    return 0;
}

myMap size==3
STL tutorial http://c.biancheng.net/stl/
Python tutorial http://c.biancheng.net/python/
C language tutorial http://c.biancheng.net/c/

Member methodfunction
begin()Returns a two-way iterator pointing to the first (note, the first ordered) key value pair in the container. If the map container is qualified with const, the method returns a bidirectional iterator of type const.
end()Returns a two-way iterator that points to the location after the last element of the container (note that it is the last one in order), usually used in conjunction with begin(). If the map container is qualified with const, the method returns a bidirectional iterator of type const.
rbegin()Returns a reverse bidirectional iterator pointing to the last (note, the last ordered) element. If the map container is qualified with const, the method returns an inverse bidirectional iterator of type const.
rend()Returns a reverse bidirectional iterator that points to the previous position of the first (note, the first ordered) element. If the map container is qualified with const, the method returns an inverse bidirectional iterator of type const.
cbegin()The function is the same as begin(), but the const attribute is added on the basis of it, which can not be used to modify the key value pairs stored in the container.
cend()The function is the same as that of end(), but the const attribute is added on the basis of it, which can not be used to modify the key value pairs stored in the container.
crbegin()The function is the same as rbegin(), but the const attribute is added on the basis of rbegin(), which can not be used to modify the key value pairs stored in the container.
crend()The function is the same as that of rend(), but the const attribute is added on the basis of it, which can not be used to modify the key value pairs stored in the container.
find(key)Find the key value pair with key in the map container. If it is found successfully, return the bidirectional iterator pointing to the key value pair; Otherwise, the same iterator as the end() method is returned. In addition, if the map container is qualified with const, the method returns a bidirectional iterator of type const.
lower_bound(key)Returns a bidirectional iterator pointing to the first key value pair greater than or equal to key in the current map container. If the map container is qualified with const, the method returns a bidirectional iterator of type const.
upper_bound(key)Returns an iterator pointing to the first key value pair greater than key in the current map container. If the map container is qualified with const, the method returns a bidirectional iterator of type const.
equal_range(key)This method returns a pair object (containing two bidirectional iterators), where pair.first and lower_ The return value of the bound () method is equivalent, pair.second and upper_ The return value of the bound () method is equivalent. That is, the method will return a range containing key value pairs (the map container key value pairs are unique, so the range contains at most one key value pair).
empty() If the container is empty, return true; Otherwise, false.
size()Returns the number of key value pairs stored in the current map container.
max_size()Returns the maximum number of key value pairs that the map container can hold. The return values are different for different operating systems.
operator[]The [] operator is overloaded in the map container. As long as you know the value of the key of a key value pair in the map container, you can directly obtain the corresponding value through the key like obtaining the elements in the array.
at(key)Find the value corresponding to the key key in the map container. If it is not found, the function will raise out_of_range exception.
insert()Insert key value pairs into the map container.
erase()Delete the specified location, key value or key value pair in the specified area of the map container. The following chapters will focus on this method.
swap()Exchange the key value pairs stored in the two map containers, which means that the two key value pairs of the operation must be of the same type.
clear()Empty all key value pairs in the map container, even if the size() of the map container is 0.
emplace()Constructs a new key value pair at the specified location in the current map container. The effect is the same as inserting key value pairs, but it is more efficient.
emplace_hint()Essentially, the method constructs a new key value pair in the map container in the same way as replace (), except that the user must provide the method with an iterator indicating the generation position of the key value pair as the first parameter of the method.
count(key)In the current map container, find the number of key value pairs with key and return. Note that since the key value of each key value pair in the map container is unique, the maximum return value of this function is 1.

iterator traversal

#include <iostream>
#include <map>      // pair
#include <string>       // string
using namespace std;
int main() {
    //Create and initialize the map container
    std::map<std::string, std::string>myMap{ {"STL course","http://c.biancheng.net/stl/"},{"C language tutorial " http://c.biancheng.net/c/ "} };
    //Call the begin()/end() combination to traverse the map container
    for (auto iter = myMap.begin(); iter != myMap.end(); ++iter) {
        cout << iter->first << " " << iter->second << endl;
    }
    return 0;
}

find method

#include <iostream>
#include <map>      // pair
#include <string>       // string
using namespace std;
int main() {
    //Create and initialize the map container
    std::map<std::string, std::string>myMap{ {"STL course","http://c.biancheng.net/stl/"},
                                             {"C Language course","http://c.biancheng.net/c/"},
                                             {"Java course","http://c.biancheng.net/java/"} };
    //Find key value pairs whose key is Java tutorial
    auto iter = myMap.find("Java course");
    //Start with iter and traverse the map container
    for (; iter != myMap.end(); ++iter) {
        cout << iter->first << " " << iter->second << endl;
    }
    return 0;
}

Get value method

#include <iostream>
#include <map>      // map
#include <string>   // string
using namespace std;
int main() {
    //Create and initialize the map container
    std::map<std::string, std::string>myMap{ {"STL course","http://c.biancheng.net/stl/"},
                                             {"C Language course","http://c.biancheng.net/c/"},
                                             {"Java course","http://c.biancheng.net/java/"} };
    string cValue = myMap["C Language course"];
    cout << cValue << endl;
    return 0;
}
#include <iostream>
#include <map>      // map
#include <string>   // string
using namespace std;
int main() {
    //Create and initialize the map container
    std::map<std::string, std::string>myMap{ {"STL course","http://c.biancheng.net/stl/"},
                                             {"C Language course","http://c.biancheng.net/c/"},
                                             {"Java course","http://c.biancheng.net/java/"} };
    cout << myMap.at("C Language course") << endl;
    //The following line of code will throw an out_of_range exception
    //Cout < < mymap. At ("Python tutorial") < < endl;
    return 0;
}

In addition to using the [] operator to add new key values to the map container, the map class template also provides   insert()   Member method, which is specifically used to insert new key value pairs into the map container.

#include <iostream>
#include <map>  //map
#include <string> //string
using namespace std;
int main()
{
    //Create an empty map container
    std::map<string, string> mymap;
   
    //Create a real key value pair variable
    std::pair<string, string> STL = { "STL course","http://c.biancheng.net/stl/" };
   
    //Create a pair object that receives the value returned by the insert() method
    std::pair<std::map<string, string>::iterator, bool> ret;
   
    //Insert STL. Since STL is not a temporary variable, it will pass parameters in the first way
    ret = mymap.insert(STL);
    cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
    //Pass a temporary key value pair variable as an R-value reference
    ret = mymap.insert({ "C Language course","http://c.biancheng.net/c/" });
    cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
    //Sample of insertion failure
    ret = mymap.insert({ "STL course","http://c.biancheng.net/java/" });
    cout << "ret.iter = <{" << ret.first->first << ", " << ret.first->second << "}, " << ret.second << ">" << endl;
    return 0;
}

Ret.iter = < {STL tutorial, http://c.biancheng.net/stl/ }, 1>
Ret.iter = < {C language tutorial, http://c.biancheng.net/c/ }, 1>
Ret.iter = < {STL tutorial, http://c.biancheng.net/stl/ }, 0>

  • For the insert() method with successful insertion, the pair object returned by it contains an iterator pointing to the newly inserted key value pair and a bool variable with a value of 1
  • For the insert() method that fails to insert, a pair object will also be returned, including a key value pair pointing to the "STL tutorial" key in the map container and a bool variable with a value of 0.

set type

#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
    //Create an empty set container
    std::set<std::string> myset;
    //An empty set container does not store any elements
    cout << "1,myset size = " << myset.size() << endl;
    //Insert a new element into the myset container
    myset.insert("http://c.biancheng.net/java/");
    myset.insert("http://c.biancheng.net/stl/");
    myset.insert("http://c.biancheng.net/python/");
    cout << "2,myset size = " << myset.size() << endl;
    //Using a bidirectional iterator, traverse myset
    for (auto iter = myset.begin(); iter != myset.end(); ++iter) {
        cout << *iter << endl;
    }
    return 0;
}

1,myset size = 0
2,myset size = 3
http://c.biancheng.net/java/
http://c.biancheng.net/python/
http://c.biancheng.net/stl/

begin()Returns a two-way iterator pointing to the first (note, the first ordered) element in the container. If the set container is qualified with const, the method returns a two-way iterator of type const.
end()Returns a two-way iterator pointing to the position after the last element of the container (note that it is the last one in order), which is usually used in combination with begin(). If the set container is qualified with const, the method returns a two-way iterator of const type.
rbegin()Returns an inverse bidirectional iterator pointing to the last (note, the last ordered) element. If the set container is qualified with const, the method returns an inverse bidirectional iterator of type const.
rend()Returns a reverse two-way iterator pointing to the position before the position of the first (note, the first ordered) element. If the set container is qualified with const, the method returns a reverse two-way iterator of type const.
cbegin()The function is the same as that of begin(), but the const attribute is added on the basis of it, which cannot be used to modify the element value stored in the container.
cend()The function is the same as that of end(), but the const attribute is added on the basis of it, which cannot be used to modify the element value stored in the container.
crbegin()The function is the same as rbegin(), but the const attribute is added on the basis of rbegin(), which can not be used to modify the element value stored in the container.
crend()The function is the same as that of rend(), but the const attribute is added on its basis, which can not be used to modify the element value stored in the container.
find(val)Find an element with value val in the set container. If it is found successfully, it returns a bidirectional iterator pointing to the element; otherwise, it returns the same iterator as the end() method. In addition, if the set container is qualified with const, the method returns a bidirectional iterator of const type.
lower_bound(val)Returns a bidirectional iterator pointing to the first element greater than or equal to val in the current set container. If the set container is qualified with const, the method returns a bidirectional iterator of const type.
upper_bound(val)Returns an iterator pointing to the first element greater than val in the current set container. If the set container is qualified with const, the method returns a two-way iterator of const type.
equal_range(val)This method returns a pair object (including two bidirectional iterators), where the return values of pair.first and lower_bound() methods are equivalent, and the return values of pair.second and upper_bound() methods are equivalent. That is, this method will return a range containing elements with value val (each element in the set container is unique, so the range contains at most one element).
empty()Returns true if the container is empty; otherwise, false.
size()Returns the number of elements in the current set container.
max_size()Returns the maximum number of elements that the set container can hold. The return values are different for different operating systems.
insert()Inserts an element into the set container.
erase()Delete the elements stored in the set container.
swap()Swap all elements stored in the 2 set containers. This means that the 2 set containers for the operation must be of the same type.
clear()Empty all elements in the set container, that is, make the size() of the set container 0.
emplace()Construct a new element directly at the specified position in the current set container. Its effect is the same as insert(), but it is more efficient.
emplace_hint()In essence, it is the same as the way empty () constructs a new element in the set container, except that the user must provide an iterator indicating the generation location of the new element as the first parameter of the method.
count(val)In the current set container, find the number of elements with the value val and return it. Note that since the value of each element in the set container is unique, the maximum return value of this function is 1.

  insert method

#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
    //Create and initialize the set container
    std::set<std::string> myset;
    //Ready to accept the return value of insert()
    pair<set<string>::iterator, bool> retpair;
    //Common reference value transfer method is adopted
    string str = "http://c.biancheng.net/stl/";
    retpair = myset.insert(str);
    cout << "iter->" << *(retpair.first) << " " << "bool = " << retpair.second << endl;
    //The right value reference method is adopted
    retpair = myset.insert("http://c.biancheng.net/python/");
    cout << "iter->" << *(retpair.first) << " " << "bool = " << retpair.second << endl;
    return 0;
}

iter->http://c.biancheng.net/stl/ bool = 1
iter->http://c.biancheng.net/python/ bool = 1

#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
    //Create and initialize the set container
    std::set<std::string> myset;
    //Ready to accept the return value of insert()
    set<string>::iterator iter;
    //Common reference value transfer method is adopted
    string str = "http://c.biancheng.net/stl/";
    iter = myset.insert(myset.begin(),str);
    cout << "myset size =" << myset.size() << endl;
    //The right value reference method is adopted
    iter = myset.insert(myset.end(),"http://c.biancheng.net/python/");
    cout << "myset size =" << myset.size() << endl;
    return 0;
}

myset size =1
myset size =2

Delete element erase

//Delete the element with val in the set container
size_type erase (const value_type& val);
//Delete the element pointed to by the position iterator
iterator  erase (const_iterator position);
//Delete all elements in the [first,last) interval
iterator  erase (const_iterator first, const_iterator last);

#include <iostream>
#include <set>
#include <string>
using namespace std;
int main()
{
    //Create and initialize the set container
    std::set<int>myset{1,2,3,4,5};
    cout << "myset size = " << myset.size() << endl;
   
    //1) Call the erase() method of the first format
    int num = myset.erase(2); //Delete element 2, myset={1,3,4,5}
    cout << "1,myset size = " << myset.size() << endl;
    cout << "num = " << num << endl;
    //2) Call the erase() method of the second format
    set<int>::iterator iter = myset.erase(myset.begin()); //Delete element 1, myset={3,4,5}
    cout << "2,myset size = " << myset.size() << endl;
    cout << "iter->" << *iter << endl;
    //3) Call the erase() method of the third format
    set<int>::iterator iter2 = myset.erase(myset.begin(), --myset.end());//Delete element 3,4, myset={5}
    cout << "3,myset size = " << myset.size() << endl;
    cout << "iter2->" << *iter2 << endl;
    return 0;
}

myset size = 5
1,myset size = 4
num = 1
2,myset size = 3
iter->3
3,myset size = 1
iter2->5

Source: Detailed explanation of C++ STL associative container

Posted by shmeeg on Thu, 07 Oct 2021 23:48:54 -0700