Detailed usage of set in STL !!!!, How to use set in stl

Source: Internet
Author: User

Detailed usage of set in STL !!!!, How to use set in stl

1. About set

C ++ STL has been widely praised and used by many people. It not only provides convenient containers such as vector, string, and list, more importantly, STL encapsulates many complex data structure algorithms and a large number of common data structure operations. Vector encapsulation array, list encapsulates the linked list, map and set encapsulate Binary Trees, etc. When encapsulating these data structures, STL follows the programmer's usage habits, common Operations provided by member functions, such as insert, sort, delete, and search. It makes users feel familiar with STL usage.

Set-related containers must be described. Set is used as a container to store data types of the same data type, and can retrieve data from a dataset. The values of each element in set are unique, in addition, the system can automatically sort elements based on their values. It should be noted that the value of the number element in the set cannot be changed directly. In C ++ STL, the standard associated containers set, multiset, map, and multimap use a very efficient balanced binary tree for retrieval: red/black, it also becomes a Red-Black Tree ). The statistical performance of the RB tree is better than that of the general balanced binary tree, so STL selects the internal structure of the associated container.

 There are several questions about set:

(1) Why is the insert/delete efficiency of map and set higher than that of other sequential containers?

Most people say that it is very simple, because for associated containers, memory copying and memory moving are not required. That's true. All elements in the set container are stored as nodes. The node structure of the set container is similar to that of the linked list, pointing to the parent node and the child node. The structure may be as follows:

 

A
/\
B C
/\/\
D E F G

Therefore, you only need to perform a slight transformation during the insertion, and point the node pointer to the new node. The deletion process is similar. After a slight transformation, it is okay to direct the pointer to the deleted node to another node. All the operations here are pointer exchange, which has nothing to do with memory movement.

(2) Why does the previously saved iterator not expire after each insert operation?

Iterator is equivalent to a pointer to a node. If the memory is not changed, how can the pointer to the memory become invalid? (of course, the deleted element itself is no longer valid ). The pointer may be invalid for each deletion or insertion of a vector, and push_back is called to insert data at the end. To ensure the continuous storage of internal data, the block pointed to by iterator may have been overwritten by other memory or the memory has been released. Even when push_back is used, the internal space of the container may be insufficient and a larger memory is required. Only the previous memory is released and a larger memory is applied, copy the existing data elements to the new memory, and put the elements to be inserted at the end, so the previous memory pointer is naturally unavailable. Especially when using algorithms such as find, remember this principle: Do not use expired iterator.

(3) when the number of data elements increases, how does the set insertion and search speed change?

If you know the relationship between log2, you should thoroughly understand this answer. In set, binary search is used. That is to say, if there are 16 elements, you can find the result by comparing up to 4 times. There are 32 elements, up to 5 comparisons. What about 10000? The maximum number of comparisons is log10000, and the maximum number is 14. What if it is 20000 elements? Up to 15 times. As you can see, when the data size doubles, the number of searches is only one more time, and the search time is 1/14 more. After you understand this truth, you can put elements in it with peace of mind.

Set usage:

Begin (), returns the first element of the set container

End (), returns the last element of the set container.

Clear (), delete all elements in the set container

Empty () to determine whether the set container is empty

Max_size () returns the maximum number of elements that a set container may contain.

Size (), returns the number of elements in the current set container

Rbegin, returns the same value as end ()

Rend (), returns the same value as rbegin ()

Simple operation example:

# Include <iostream> # include <set> using namespace std; int main () {set <int> s; s. insert (1); s. insert (2); s. insert (3); s. insert (1); cout <"set size value:" <s. size () <endl; cout <"set maxsize value:" <s. max_size () <endl; cout <"the first element in set is:" <* s. begin () <endl; cout <"the last element in set is:" <* s. end () <endl; s. clear (); if (s. empty () {cout <"set is empty !!! "<Endl ;}cout <" set size value: "<s. size () <endl; cout <"set maxsize value:" <s. max_size () <endl; return 0 ;}

Running result:


Summary:After inserting 3, although a 1 is inserted, we find that the last value in the set is still 3, which is set. Also note that the begin () and end () functions do not check whether the set is empty. before using it, it is best to use empty () to check whether the set is empty.

 

Count ()Used to find the number of times a key value appears in the set. This function is not very practical in set, because a key value can only appear 0 or 1 time in set, so it becomes to judge whether a key value has appeared in set.

Sample Code:

# Include <iostream> # include <set> using namespace std; int main () {set <int> s; s. insert (1); s. insert (2); s. insert (3); s. insert (1); the number of occurrences of 1 in the cout <"set is:" <s. count (1) <endl; cout <"set 4 times:" <s. count (4) <endl; return 0 ;}

Press Ctrl + C to copy the code

Running result:

 

Performance_range ()Returns a pair of locators, indicating the first element greater than or equal to the given key value and the first element greater than the given key value. The returned value is of the pair type, if the returned result of this pair of locators fails, it will be equal to the value of end. What is the specific purpose of this? I haven't met it yet ~~~

Sample Code:

# Include <iostream> # include <set> using namespace std; int main () {set <int> s; set <int >:: iterator iter; for (int I = 1; I <= 5; ++ I) {s. insert (I) ;}for (iter = s. begin (); iter! = S. end (); ++ iter) {cout <* iter <"" ;}cout <endl; pair <set <int >:: const_iterator, set <int>:: const_iterator> pr; pr = s. optional _range (3); cout <"the first number greater than or equal to 3 is:" <* pr. first <endl; cout <"the first number greater than 3 is:" <* pr. second <endl; return 0 ;}

Running result:

 

Erase (iterator) to delete the value pointed to by iterator

Erase (first, second), delete the value between the first and second locators

Erase (key_value), delete the key value key_value

Let's look at the program:

# Include <iostream> # include <set> using namespace std; int main () {set <int> s; set <int >:: const_iterator iter; set <int> :: iterator first; set <int >:: iterator second; for (int I = 1; I <= 10; ++ I) {s. insert (I);} // The first type deletes s. erase (s. begin (); // The second type deletes first = s. begin (); second = s. begin (); second ++; s. erase (first, second); // The third type deletes s. erase (8); cout <"after deletion, the elements in the set are:"; for (iter = s. begin (); iter! = S. end (); ++ iter) {cout <* iter <"" ;}cout <endl; return 0 ;}

Running result:

Summary:The delete operation in set does not carry out any error checks, such as whether the positioner is legal or not. Therefore, you must pay attention to it when using it.

Find (), Returns the value of the given value locator, if not found, returns end ().

Sample Code:

#include <iostream>#include <set>using namespace std;int main(){    int a[] = {1,2,3};    set<int> s(a,a+3);    set<int>::iterator iter;    if((iter = s.find(2)) != s.end())    {        cout<<*iter<<endl;    }    return 0;}

Insert (key_value );Insert key_value into the set. The returned value is pair <set <int>: iterator, bool>. bool indicates whether the insert is successful, while iterator indicates the position of the insert, if the key_value is already in set, the key_value indicated by iterator is located in set.

Inset (first, second );Insert the element between the first and second locators into the set. The return value is void.

Sample Code:

#include <iostream>#include <set>using namespace std;int main(){    int a[] = {1,2,3};    set<int> s;    set<int>::iterator iter;    s.insert(a,a+3);    for(iter = s.begin() ; iter != s.end() ; ++iter)    {        cout<<*iter<<" ";    }    cout<<endl;    pair<set<int>::iterator,bool> pr;    pr = s.insert(5);    if(pr.second)    {        cout<<*pr.first<<endl;    }    return 0;}

Running result:

Lower_bound (key_value)Returns the first positioner greater than or equal to key_value.

Upper_bound (key_value ),Returns the last locator greater than or equal to key_value.

Sample Code:

#include <iostream>#include <set>using namespace std;int main(){    set<int> s;    s.insert(1);    s.insert(3);    s.insert(4);    cout<<*s.lower_bound(2)<<endl;    cout<<*s.lower_bound(3)<<endl;    cout<<*s.upper_bound(3)<<endl;    return 0;}

Running result:

This article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.