Container of C + +

Source: Internet
Author: User

Containers, iterators, and container adapters

The so-called container, which is the most frequently used data structures, is implemented with class templates to accommodate specific types of objects. Depending on the characteristics of the data in the container, the container can be divided into sequential (sequence) and associative (associative). The benefit of the container is that it does not require you to tell it beforehand how many objects you want to store, as long as you create a container object and make reasonable calls to the method it provides, all the processing details will be done by the container itself, it can request memory for you or free memory, and use the best algorithm to execute your command.

An iterator is a data type that examines elements within a container and iterates through the elements, providing a pointer-like function for visiting the contents of a container.

An adapter is a mechanism that enables a behavior of one thing to behave like another, and is a mechanism that enables an existing container type to work in another different abstract type. We can think of it as the interface of a container, or the template of a container. The adapter is specifically used to implement the type of container, when defining the adapter can be determined.

The following table lists the specific container classes contained in the three types of containers defined by STL:

Standard Container class

Characteristics

Sequential containers

Vector

Quick Insert and delete from behind, direct access to any element

Deque

Quick Insert and delete from front or back, direct access to any element

List

Double linked list, quick insert and delete from anywhere

Associative containers

Set

Quick Find, no duplicate values allowed

Multiset

Quick Find, allow duplicate values

Map

One-to-many mappings, fast lookup based on keywords, no duplicate values allowed

Multimap

One-to-many mappings, quick find based on keywords, allow duplicate values

Container Adapter

Stack

Last in, first out

Queue

Advanced First Out

Priority_queue

The highest priority element is always the first out-of-order

Sequential containers (sequential containers)

Define and Initialize:

In order to define an object of a container type, you must include the associated header file:

#include <vector>

#include <list>

#include <deque>

Since all containers are class templates, when we want to define a container object, we must add a pair of angle brackets after the container name, and the angle brackets provide the type of elements that are stored in the container:

Vector<string> svec;//The container is empty at this time, but it can hold a string object

A similar example:

List<int> Listint;

Deque<person> item;

All container types Define a default constructor that creates an empty container object of the specified type, and for a clearer, shorter program, the most common constructor for a container type is the default constructor, but the container class also provides the following constructor:

C c (C2);//Create a copy of the container C2 c,c and C2 must have the same container type and hold the same type of element, which applies to all containers

When you copy a container to another container, the type must match: Both the container type and the element type must match;

Vector<int> Ivec;

Vector<int> ivec2 (Ivec);

C c (b,e);//create C, whose elements are copies of the elements in the range indicated by iterators B and E, for all containers

Although it is not possible to directly copy elements from one container to another, the system allows this functionality to be implemented indirectly through a pair of iterators. Therefore, when using iterators, the same container type is not required, and the element types within the container can be different, as long as they are compatible with each other and can be replicated by converting the elements that will be copied to the element type of the new container being constructed.

Vector<string> Svec;

List<string> Slist (Svec.begin (), Svec.end ());

Vector<string>::iterator Mid=svec.begin () +svec.size ()/2;

Deque<string> Front (Svec.begin (), mid);

Deque<string> Back (Mid,svec.end ());

Because the pointer is an iterator, it allows the container to be initialized by using a pair of pointers in the built-in array:

Char *words[]={' book ', ' book ', ' book '};

size_t words_size=sizeof (words)/sizeof (char*);

List<string> Word2 (words,words+words_size);

C c (n,t); Create container C with n values of T, where the value T must be a value of the element type of the container type C, or a value that can be converted to that type, which applies only to the sequential container

List<string> slist ("Hello")//64 a "hello"

c c (n);//create container C with n values to initialize elements, only for sequential containers

List<int> IList (64);//64 elements, each of which is 0

Type constraints for elements within a container:

The container provides us with a powerful function, but also gives us some usage requirements, the sequential container element type must meet the following two constraints:

(1) The element type must be a support assignment operation

(2) An object of the element type must be able to replicate

References do not support general-purpose assignment operations, so all built-in or composite types can be used in element types in addition to reference types, and IO library types do not support assignment and replication, so all other standard library types are valid container element types in addition to the input-output (IO) standard library type. It can even be that the element itself is a container type element such as:

vector<vector<string> > lines;

Furthermore, we should understand that the above two constraints are only the minimum requirements for the container type, because some container operations have more stringent requirements on element types, and other constraints, if the element type does not support these additional demanding requirements, then we can still define a container of that type, However, you cannot use the appropriate specific action.

Iterators

An iterator provides an operation for all standard library types:

*iter returns a reference to the element pointed to by the iterator ITER

Iter->member a dereference of ITER to get a member named member in the specified element, equivalent to (*iter). Member

++iter adds 1 to ITER, which points to the next element in the container.

iter++

--iter 1 to ITER, which points to the previous element in the container.

iter--

Iter1==iter2 compares two iterators for equality, when two iterators point to one element of copper in the same container, or if they all point to the next position of the same container beyond the end, two iterators are equal

Iter1!=iter2

Of the container types in the C + + definition, only the vector and deque containers provide the following two important operations: iterator arithmetic operations, and use of except = = and! = Other than the relational operator to compare two iterators:

Iter+n

Iter-n (minus) An integer value n on an iterator that produces an iterator pointing to the nth element in front (behind) the container

Iter1+=iter2

Iter1-=iter2

Iter1-iter2

The <,<=,>,>= iterator's relational operator, which is less than the last iterator when the element pointed to by one iterator precedes the element pointed to by another iterator in the container

The C + + language uses a pair of iterators to tag the iterator scope, which points to two elements in the same container or to the next position beyond the end, typically naming them first and last, or beg and end, to mark a range of elements in the container. It is important to note that last (or end) does not point to the final element of the element range, but rather to the next position of the last element, which makes it easier for us to programmatically use: When first and last are equal, the iterator scope is empty, and when first and last are not equal, There is at least one element in the scope of the iterator, and first points to the second element in that interval:

while (first!=last)

{

++first;

}

Begin and End members

The Begin and end operations produce iterators that point to the next position of the first element and the last element within these containers

C.begin () returns an iterator that points to the first element of container C

C.end () returns an iterator that points to the next position of the last element of container C

C.rbegin () returns an inverse iterator that points to the last element of container C

C.rend () returns an inverse iterator that points to the position in front of the first element of container C

A reverse iterator is an iterator that traverses a container in reverse. In other words, the container is traversed from the last element to the first element. The inverse iterator will reverse the meaning of self-increment (and decrement): For a reverse iterator, the + + operation accesses the previous element, while the--operation accesses the next element, such as:

Each of these operations has two different versions: one is a const member and the other is a non-const member. What types these operations return depends on whether the container is const. If the container is not const, these operations return the iterator or reverse_iterator type. If the container is const, its return type is prefixed with the const_ prefix, which is the const_iterator and const_reverse_iterator types.

Adding elements to a sequential container

C.push_back (t); Adds an element with a value of t at the tail of container C, returning void type

C.push_front (t); Adds an element with a value of t at the front end of container C, returning void type

Only available for list and deque container types

C.insert (p,t); Inserts a new element with a value of t before the element pointed to by the iterator P, returning an iterator to the newly added element

C.insert (p,n,t); Inserts a new element with n values of T before the element that the iterator p points to, returning the void type

C.insert (p,b,e); Inserts an element in the range labeled by Iterators B and E before the element that the iterator p points to, returning the void type

When adding elements to a container, the system copies the element values into the container, similarly, when a new container is initialized with a section of elements, the new container holds a copy of the original element. The copied element is irrelevant to the elements in the new container, and thereafter, the value of the original element being copied is not affected when the value of the element in the container changes, and vice versa.

The size of the sequential container operation

C.size () returns the number of elements in container C. return type is C::size_type

C.max_size () returns the maximum number of elements that container C can hold, with a return type of C::size_type

C.empty () returns a Boolean value that marks whether the container size is 0

C.resize (n) Adjusts the length of the container C so that it can hold n elements, and if n <c.size (), delete the extra elements; otherwise, add a new element with value initialization
C.resize (n,t) adjusts the length of container C so that it can hold n elements. All newly added element values are T

To access elements within a container:

C.back () returns a reference to the last element of container C (note the difference from the preceding or previous end)

C.front () returns a reference to the first element of container C

The following two species are only available for vector and deque containers

C[n] Returns a reference to an element labeled N

c.at (n) returns a reference to an element with the subscript n

To delete a container element:

C.erase (p) Removes the element pointed to by the iterator P, returning an iterator that points to the element following the deleted element

C.erase (b,e) removes all elements in the range marked by Iterators B and E

C.clear () Delete all elements in iterator C

C.pop_back () Delete the last element in iterator C

C.front () Remove the first element in iterator C

Container of C + +

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.