Summary of container in C + + _c language

Source: Internet
Author: User
Tags map class reserved

Containers in C + + can be roughly divided into two broad categories: sequential containers and associated containers. The sequential container contains a sequential container adapter.
Sequential containers : Aggregates elements of a single type into containers and then stores and accesses them based on location. The main vector, list, deque (two-terminal queue). Sequential container adapters: Stack, queue, and priority_queue.
Associative containers : supports the use of keys to efficiently find and read elements. Mainly include: pair, set, map, Multiset and Multimap.
Next, in turn, for a variety of containers to do a detailed introduction.

First, sequential container

1. Sequential container definition
In order to define an object of a container type, you must first include the associated header file:
Define vector: #include <vector>
Definition list: #include <list>
Definition deque: #include <deque>

Defining examples

Vector<int> VI;
List<int> Li;
Deque<int> di;

2. Sequence container initialization

Initialization example:

Initialized to a copy of a container
vector<int> VI;
Vector<int> Vi2 (vi); Use VI to initialize VI2
//initialization as a copy of the element
char*words[] = {"Stately", "plump", "Buck", "Mulligan"};
Size_twords_size = sizeof (words)/sizeof (char*);
List<string> Words2 (words, words + words_size);
Assigns and initializes a specified number of elements
constlist<int>::size_type list_size =;
List<string> slist (List_size, "a"); strings, each is a

3, the sequential container support pointer operation

① all sequence supported pointers run

②vector and Deque Container iterators provide additional operations

③ iterator invalidation: Some container operations modify the internal state of the container or move elements within the container. Such an operation invalidates all iterators that point to the moved element, or it can invalidate other iterators at the same time. Using an invalid iterator is undefined and may result in the same problem as the dangling pointer.

④begin and END members: the begin and finish operations produce an iterator that points to the next position of the first and last elements within the container.

3. Sequential container operation

① add Element

To add an element example:

Add data list<int> IList to the container header or tail
;
Ilist.push_back (ix);//Tail add
Ilist.push_front (ix);
//Header Add///add element list<string> LST at specified position in container
;
List<string>::iterator iter = Lst.begin ();
while (CIN >> word)
iter = Lst.insert (ITER, Word);//Push_front meaning
//insert element
list<string> Slist;
String Sarray[4] = {"Quasi", "Simba", "Frollo", "Scar"};
Slist.insert (Slist.end (), ten, "a") and/or tail add 10 elements are a
list<string>::iterator slist_iter = Slist.begin ();
Slist.insert (Slist_iter, sarray+2, sarray+4);//Pointer range add

Operation of ② container size

Example:

List<int> IList (1);
Ilist.resize (15); The tail adds five elements, the values are 0
ilist.resize (25,-1);//Then the tail adds 10 elements, the element is-1
ilist.resize (5), and/or 20 elements are deleted from the tail

③ Access elements

int vector<int> VI;
for (int i=0;i<10;i++) vi.push_back (i);
cout<<vi[0]<<endl;
cout<<vi.at (0) <<endl;
cout<<vi[10]<<endl; Cross-border error
cout<<vi.at (<<endl;//) Cross-border error

④ Delete Element

Example:

Delete the first or last element
list<int> Li;
for (int i=0;i<10;i++) list.push_back (i);
Li.pop_front ()//delete the first element
li.pop_back ();//delete the last element
//Delete an element within the container
list<int>::iterator iter = Li.begin ();
if (iter!= li.end ()) li.erase (ITER);
Delete all elements in the container
li.clear ();

⑤ Assignment and Swap

List<string> SL1,SL2;
for (int i=0;i<10;i++) Sl2.push_back ("a");
Sl1.assign (Sl2.begin (), Sl2.end ());///with SL2 pointer range, SL1 10 elements are a
sl1.assign ("a");//s1 is assigned a value of 10 elements, all a

Swap Example:

Vector<string> VS1 (3); VS1 has 3 elements.
Vector<string> vs (5); VS2 has 5 elements.
Vs1.swap (VS2), after execution, the VS1 5 elements, and VS2 save 3 elements.

⑥vector Self-growth: capacity and reserve members

To increase the vector's efficiency, you don't have to redistribute space every time you add elements. Vectors are allocated more space when allocated than needed. The vector class provides two member functions: Capacity and reserve enable programmers to interact with the implementation portion of vector container memory allocations.
Capacity action: Gets the total number of elements that can be stored before the container needs to allocate more storage space
Reserve operation: tells the vector container how many elements should be reserved for storage space

The difference between capacity (capacity) and size (length): size refers to the number of elements currently owned by the container, while capacity refers to the total number of elements that the container can store before it must allocate new storage space. Capacity is larger than size in general.
Example:

Vector<int> Ivec;
cout << "ivec:size:" << ivec.size ()
<< "Capacity:" << ivec.capacity () << endl;//are 0 C3/>for (Vector<int>::size_type ix = 0; IX!= ++ix) Ivec.push_back (ix);
cout << "ivec:size:" << ivec.size ()
<< "Capacity:" << ivec.capacity () << Endl;//capa City greater than size

Reserve space can be manipulated by function reserve ()

On the basis of a previous piece of code
Ivec.reserve (Ivec.capacity () +50)//50 additional reserved space for Ivec

In addition: If you do not manually reserve space, each time the vector container has to allocate new storage space, double the allocation policy for the current capacity to redistribute.

4, the selection of containers
general rules for choosing a container type:
① If your program requires random access to elements, you should use a vector or deque container.
② If your program must insert or delete elements in the middle of the container, you should use the list container.
③ If the program is not in the middle of the container, but inserts or deletes elements at the beginning or end of the container, the Deque container should be used.
④ If you simply insert an element in the middle of the container while reading the input, then you need to randomly access the elements, you can consider reading the elements into a list container as you enter them, then reordering the container so that it fits in sequential access, and then copying the sorted list container to a vector container.
If the program requires random access and must insert or delete elements in the middle of the container, the choice of which container depends on the relative cost of the following two operations: the cost of randomly accessing the list container element, and the cost of copying elements when inserting/deleting elements in a vector or deque container. Generally, the dominant operation in the application (more in the program using an access operation or an Insert/delete operation) will determine what type of container should be.

5. Container Adapter

Common operations and types for ① adapters

Initialization of the ② adapter
All adapters have two constructors defined: The default constructor is used to create an empty object, and a constructor with one container parameter takes a copy of the parameter container as its underlying value.

The default stack and queue are implemented based on the Deque container, while the priority_queue is implemented on the vector container.
Example:

Vector<int> VI;
Deque<int> DEQ;
stack<int> Stk (DEQ); Use DEQ to initialize STK
stack<int> stk1 (vi);//Error

Operation of the ③ adapter
Stack adapters:

Queues and Priority queues:

Second, the related container

1, pair

Actions provided by the ①pairs type

②pairs type definition and initialization

pair<string, string> Test ("A", "B");

③pairs Other actions

Pairs object's operations
string Firstbook;
if (Author.first = = "James" && Author.second = = "Joyce") Firstbook = "Stephen Hero";
Generation of new pair objects
pair<string, string> Next_auth;
Next_auth = Make_pair ("A", "B");//The first method
Next_auth = pair<string, string> ("A", "B");//The second method
cin> The third method of >next_auth.first>>next_auth.second;//

2, Map

A map is a collection of key-value pairs. A map type is generally understood to be an associative array: You can use a key as a subscript to get a value, just as the built-in array type does. The essence of an association is that the value of an element is associated with a particular key, not by the position of the element in the array.

Definition of ①map Object

Map<string, int> Word_count;

This statement defines a map object named Word_count, which is indexed by a type of string and the associated value is int.
Map access: When you dereference an iterator, you get a reference pointing to a Pair<const string,int> class in the container
The value of the type. Accessed through a pair type of access.

Constructor for ②map

Constraints on ③ key types
When using an associative container, its key has not only one type, but also a related comparison function. The comparison function used must define a strict weak sort on the key type (strict weak ordering): It can be understood as "less than" on the key type data, although you can actually choose to design the comparison function more complex.
For key types, the only constraint is that the < operator must be supported, and no requirement is made as to whether other relationships or equality operations are supported.

Types defined by the ④map class

Value_type is the key of the stored element and the pair type of the value, and the key is const. For example, the value_type of the Word_count array is the Pair<const string,int> type. Value_type is a pair type whose value members can be modified, but key members cannot be modified.

⑤map add Element
There are two ways to add elements: 1, first get the element with the subscript operator, then assign a value of 2 to the acquired element, and use the Insert member function to implement the
The subscript operation adds an element: If the key is already in the container, the map's subscript operation behaves the same as the vector's subscript operation: Returns the value associated with the key. The map container creates a new element for the key, and inserts it into this map object, only if the key you are looking for does not exist. At this point, the associated value is initialized with the value: the element of the class type is initialized with the default constructor, and the elements of the built-in type are initialized to 0.
Insert operation:

Example:

Word_count.insert (map<string, Int>::value_type ("Anna", 1));
Word_count.insert (Make_pair ("Anna", 1));

The return value of the insert: A pair object that contains an iterator and a bool value, where the iterator points to an element in the map that has the corresponding key, and the bool value indicates whether the element was inserted. If the key is already in the container, its associated value remains unchanged and the bool value returned is true. In both cases, the iterator will point to the element that has the given key.

Pair<map<string, int>::iterator, bool> ret =
Word_count.insert (Make_pair (Word, 1));

RET stores the pair object returned by the Insert function. The pair's primary member is a map iterator that points to the inserted key. Ret.first gets the map iterator from the pair object returned by the insert; Ret.second returns whether the element was inserted from insert.

⑥ find and read elements in a map
There is a dangerous side effect of using subscripts in a map: If the key is not in the map container, the subscript operation inserts a new element with that key. So the map container provides two operations: Count and find, which check whether a key exists without inserting the key.

int occurs = 0;
if (Word_count.count ("Foobar")) occurs = word_count["Foobar"];
Map<string,int>::iterator it = word_count.find ("Foobar");
if (it!= word_count.end ()) occurs = it->second;

⑦ remove elements from a map object

String Removal_word = "a";
if (Word_count.erase (Removal_word))
cout << "OK:" << removal_word << "removed\n";
else cout << "oops:" << removal_word << "not found!\n";

3, set

Definition and use of ①set containers
Each key of the set container can only correspond to one element. When you initialize a set object with a range of elements, or when you insert a set of elements into a set object, you actually add only one element to each key.

Vector<int> Ivec;
for (Vector<int>::size_type i = 0; I!= ++i) {
ivec.push_back (i);
Ivec.push_back (i);
}
Set<int> Iset (Ivec.begin (), Ivec.end ());
cout << ivec.size () << Endl; 20
cout << iset.size () << Endl;//10

② add elements to set

Set<string> Set1;
Set1.insert ("the"); The first method: Directly add
set<int> Iset2;
Iset2.insert (Ivec.begin (), Ivec.end ());//second method: through the pointer iterator

③ gets the element from the set
The set container does not provide subscript operators. To obtain an element from a set by using a key, use the find operation. If you simply decide whether an element exists, you can also use the count operation to return the number of elements in the set that correspond to that key. Of course, for the set container, the return value of Count can only be 1 (the element exists) or 0 (the element does not exist)

Set<int> Iset;
for (int i = 0; i<10; i++) Iset.insert (i);
Iset.find (1)//return pointer to element content 1
iset.find (11)//Return pointer iset.end ()
iset.count (1)//present, return 1
iset.count (11)/ /does not exist, return 0

3, Multimap and Multiset
the elements of the associated container map and set are stored sequentially. and Multimap and Multset are the same. Therefore, in the Multimap and Multiset containers, if a key corresponds to multiple instances, those instances are stored adjacent to the container. Iterating through the Multimap or Multiset container ensures that all elements associated with a particular key are returned in turn.

Associative container operations for ① iterators

The above is the entire content of this article, I hope to help you learn.

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.