C + + Set container

Source: Internet
Author: User

A summary of the set container in STL

1. About set (header file:<set>)

C + + STL has been widely praised, also used by many people, not only to provide such as vector, String, list and other convenient containers, more importantly, STL encapsulates a lot of complex data structure algorithms and a large number of commonly used data structure operations. Vector package Array, list encapsulates the linked list, map and set encapsulated two fork tree, in the encapsulation of these data structures, STL in accordance with the use of the programmer's habits, as a member function of the common operations, such as: Insert, sort, delete, find and so on. Let the user in the STL use process, do not feel unfamiliar.

For set, it must be stated that the set associative container. Set as a container is also used to store the data type of the same data type, and can be extracted from a data collection, the value of each element in the set is unique, and the system can be automatically sorted according to the value of the element. It should be noted that the value of the elements in the set can not be changed directly. The standard associative container set, multiset, map, Multimap inside C + + STL is a very efficient balanced retrieval binary tree: Red-black trees, also become RB trees (red-black tree). The statistical performance of RB Tree is better than that of general balanced binary tree, so the STL is chosen as the internal structure of the associative container.

There are a few questions about set:

(1) Why is the insertion and deletion efficiency of map and set higher than with other sequence containers?

Most people say it's simple because there's no need for memory copy and memory movement for associative containers. That's right, that's true. All elements within a set container are stored as nodes, with a node structure similar to that of a linked list, pointing to parent and child nodes. The structure chart might look like this:

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

As a result, you just need to make a little transformation, and point the pointer to the new node. Delete the same time, a little change after the pointer to the node to point to the other node is OK. All that is done here is that the pointer is swapped out, and the memory movement is not related.

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

Iterator here is the equivalent of a pointer to a node, the memory does not change, the pointer to the memory is how to invalidate it (of course, the deleted element itself has been invalidated). Each time the pointer is deleted and inserted, it is possible for the cursor to fail relative to the vector, and the call Push_back at the end of the insertion. Because in order to ensure the continuous storage of internal data, the iterator pointed to the block within the deletion and insertion process may have been overwritten by other memory or memory has been freed. Even when the push_back, the container internal space may not be enough, need a new larger memory, only the previous memory freed, request new larger memory, copy the existing data elements to the new memory, and finally put the elements need to be inserted into the last, then the previous memory pointer is naturally unusable. In particular, when working with algorithms such as find, keep this principle in mind: do not use outdated iterator.

(3) How does the set insert and search speed change when the number of data elements increases?

If you know log2 's relationship, you should have a thorough understanding of the answer. Finding in set is using binary lookup, that is, if there are 16 elements, you will need to compare up to 4 times to find the result, 32 elements, and a maximum of 5 times. So there are 10,000 of them? The maximum number of comparisons is log10000, up to 14, and 20,000 if it is a single element. Up to 15 times. See, when the amount of data increases by one time, the number of searches is only 1 more times, more than 1/14 of the search time. Once you understand this, you can safely put the elements inside.

Common methods in 2.set

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

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

Clear () to delete all the elements in the set container

Empty () to determine if the set container is null

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

Size () to return the number of elements in the current set container

Rbegin, the return value is the same as end ()

Rend (), the value returned is the same as Rbegin ()

Write a program to practice these simple operations:

#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 size value of the cout<< "set is:" <<s.size () <<endl;
The value of cout<< "set MAXSIZE is:" <<s.max_size () <<endl;
The first element in the cout<< "set is:" <<*s.begin () <<endl;
The last element in the cout<< "set is:" <<*s.end () <<endl;
S.clear ();
if (S.empty ())
{
cout<< "Set is empty!!! "<<endl;
}
The size value of the cout<< "set is:" <<s.size () <<endl;
The value of cout<< "set MAXSIZE is:" <<s.max_size () <<endl;
return 0;
}

Operation Result:

Summary: insert 3 after inserting a 1, but we found that the last value in set is still 3 ha, this is set. Also note that the Begin () and end () functions do not check if set is empty, and it is best to use empty () before use to verify that the set is empty.

count () is used to find the number of occurrences of one of the key values in the set. This function is not very useful in set, because a key value can only occur 0 or 1 times in set, which makes it possible to determine if a key value has occurred in set.

Example 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 in cout<< "Set 1 is:" <<s.count (1) <<endl;
The number of occurrences in cout<< "Set 4 is:" <<s.count (4) <<endl;
return 0;
}

Operation Result:

Equal_range () , returns a pair of locators that represent the first element greater than or equal to the given key value and the first element greater than the given key value, which is a pair type and, if one of the pair locators fails, equals the value of end (). I haven't met the specific purpose of this.

Example 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.equal_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;
}

Operation Result:

Erase (iterator), remove the value that the locator iterator points to

Erase (First,second), remove the value between the locator first and second

Erase (Key_value), remove the value key_value the key value

Check out 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 <=; ++i)
{
S.insert (i);
}
The first kind of deletion
S.erase (S.begin ());
The second kind of deletion
First = S.begin ();
Second = S.begin ();
second++;
second++;
S.erase (First,second);
The third kind of deletion
S.erase (8);
cout<< "The element in the set after deletion is:";
for (iter = S.begin (); ITER! = S.end (); ++iter)
{
cout<<*iter<< "";
}
cout<<endl;
return 0;
}

Operation Result:

Summary:The delete operation in set is not to do any error checking, such as whether the locator is legitimate and so on, so use when you must pay attention to.

find () , returns the given value of the locator, and returns end () if it is not found.

Example code:

#include <iostream>
#include <set>

using namespace Std;

int main ()
{
int a[] = {n/a};
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 set, the return value is Pair<set<int>::iterator,bool>,bool indicates whether the insertion was successful, and iterator represents the insertion position, if Key_ Value is already in set, then iterator represents the position of the key_value in set.

inset (first,second); Inserts the element between the locator first and second into the set, and the return value is void.

Example code:

#include <iostream>
#include <set>

using namespace Std;

int main ()
{
int a[] = {n/a};
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;
}

Operation Result:

Lower_bound (key_value) , returns the first locator greater than or equal to Key_value

Upper_bound (key_value), returns the last locator greater than or equal to Key_value

Example 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;
}

Operation Result:

C + + Set container

Related 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.