C + + Standard library learning notes (Container) __c++

Source: Internet
Author: User

Disclaimer: All content of this blog is from the C + + standard library-self-taught tutorials and reference Manual (second Edition) English edition. If reproduced, it must be accompanied by this statement, and indicate the source.
STL creates a list of generic containers to meet different needs



* * One, containers

**
1. Vector
Using vectors requires adding header files < Vector>,vector also included in Std namespace.
All of the vectors ' functions can be found here.
Here are some of the commonly used functions in the verbose.
Begin (), End (), front (), and Back (): The first two are used to get the second and last iterators, and the latter two are used to get the first and last elements.
Push_back (), Pop_back (): Add, delete the last element.
Resize () resets the vector size and can specify the value after the reset. This reset, however, takes only the n elements that precede it.
[], at (), for indexing.
Data (), which returns the first address in the vector in which the user stores the information.
Vector use is fairly simple and widely used. However, if data management is simple and the number of data is unchanged, it is recommended to use arrays directly for greater efficiency.

2, Deque
Deque is the abbreviation for "double-ended queue", a two-way array that can be stretched or shortened at both ends. So inserting the data at both ends is very fast, but inserting it in the middle is slow because some elements need to move the location. Deque is a two-way nature more than a vector.

#include <iostream>
#include <vector>
#include <deque>
int main ()
{
    std:: Vector<int> vInt;
    Vint.push_back (5201314);

    std::d eque<double> dqdouble;
    for (int i = 0; i < 8; ++i)
    {
        if (i% 2 = 0)
            dqdouble.push_back (i * 1.0);
        else
        {
            Dqdouble.push_front (i * 1.0);
        }
    for (auto iter:dqdouble)
        std::cout << iter << "  ";
    Std::cout << Std::endl;
}

3, Array
Array is a container that the STL provides to manage a fixed size. Therefore, when used, its size cannot be changed. This is similar to a normal array and cannot be dynamically allocated. The c++11 array also does not support multidimensional arrays. It doesn't feel very useful.

4, List
In c++11 there are two kinds of lists, one is List<>, it is a two-way linked list, there is a forward_list;
The advantage of using a list is that inserting or deleting an element takes a very short time because it only needs to change the pointer without moving the element. However, the list does not support random access, which can be translated for random access. , which means that it cannot get the element through the index, only to be deduced from the first. The problem with this is that it may take a long time to get the last element when the list is very long. Forward_list allows the list to grow only in one direction, and others similar to list<>.

int main ()
{
    std::list<char> cList;
    for (char c = ' a '; c <= ' z '; ++c)
        Clist.push_back (c);
    for (auto &elem:clist)
        std::cout << elem << ";
    Std::cout << Std::endl;
    return 0;
}
second, associative containers

Associative containers automatically sorts the elements according to a particular collation, and the elements may be of any type or pair. By default, it uses the operator "<" to sort ordinary value (or key or value inside pair). However, users can also customize the collation.

Associative containers Typical implementation is a binary tree. Each element has only one parent node and two child nodes (or No child nodes). Its main advantage is to find Fast.


All associative containers have an optional template parameter for sorting.

int main ()
{
    std::multiset<std::string> cities{
    "Braunschweig", "Hanover", "Frankfurt", "New York" ,
    "Chicago", "Toronto", "Paris", "Frankfurt"
};
    Print each element: for
    (const auto& elem:cities) {
        std::cout << elem.data () << "";//the book is directly Std::cout << elem << ""; but VS2013 the error, I changed the normal operation.
    }
    Std::cout << Std::endl;

    Insert additional values:
    Cities.insert ({"London", "Munich", "Hanover", "Braunschweig"});
    Print each element: for
    (const auto& elem:cities) {
        std::cout << elem.data () << "";
    }
    std::cout << Std::endl;
}

The output results are:
Braunschweig Chicago Frankfurt Frankfurt Hanover New York Paris Toronto
Braunschweig Braunschweig Chicago Frankfurt Frankfurt Hanover-Hanover London Munich New York Paris Toronto
Please press any key to continue ...

Here is an example of Multimap:

int main ()
{
    multimap<int, string> coll = {5, "tagged"},
    {2, "a"},
    {1, "this"},
    {4, " "},
    {6," strings "},
    {1," is "},
    {3," Multimap "}}; 
    Here the books are
    /*multimap<int, string> coll;//container for int/string values
    //Inserts some elements in Arbitr ARY order
    //-a value with key 1 gets inserted twice
    coll = {5, ' tagged '},
    {2, ' a '}, {
    1, ' this "},
    {4," of "},
    {6," strings "},
    {1," is "},
    {3," Multimap "}};*///But the error is not initialized.  CPP reference the use of the Make_pair mode
    //Print all element values
    //-element member second are the value for
    (auto Elem:coll) {
        cout << elem.second.data () << Endl;//This book is directly using the Elem.second to output, but VS2013 error
    }
    cout << Endl;
}
third, Unordered containers

unordered containers, as the name suggests, inside the element is not a specific sort. It's like a bag, just a load of stuff, but this thing is not known in any part of the bag. If there are two of such containers, even if you put the data, the final order may be different. A typical implementation of unordered containers is a hash table. Internally, this container is a series of linked lists. By using a hash function, the position of the element can be processed. The purpose of designing this container is to allow you to get the elements quickly because there is a hash table.

Specific types are:
anunordered Setis a collection of unordered elements, where each element could occur only
Once. Thus, duplicates are not allowed.
anunordered MultisetIs the same as a unordered set except that duplicates are allowed. Thus,
An unordered multiset could contain multiple elements that have the same value.
anunordered MapContains elements that are key/value pairs. Each key may occur only once,
So duplicate keys are not allowed. An unordered map can also is used as an associative array,
An array so has an arbitrary index type (you are 6.2.4, page 185, for details).
anunordered MultimapIs the same as a unordered map except that duplicates are allowed.
Thus, an unordered multimap could contain multiple elements that have the same key. An unordered Multimap can also is used as dictionary (for the section 7.9.7, page 383, for a example).

int main ()
{
    //need to include header file <unordered_set>
    unordered_multiset<string> cities{
    " Braunschweig "," Hanover "," Frankfurt "," New York ",
    " Chicago "," Toronto "," Paris "," Frankfurt "
};
    Print each element: for
    (const auto& elem:cities) {
        cout << elem.data () << "";
    }
    cout << Endl;
    Insert additional values:
    Cities.insert ({"London", "Munich", "Hanover", "Braunschweig"});
    Print each element: for
    (const auto& elem:cities) {
        cout << elem.data () << "";
    }
    cout << Endl;
}

Another example of a unordered_map:

int main ()
{
    //required #include <unordered_map>
    unordered_map<string, double> coll{{"Tim", 9.9},< c3/>{"Struppi", 11.77}
};
    Square the value of each element:
    for (Pair<const string, double>& elem:coll) {
        Elem.second *= elem . second;
    }
    Print each element (key and value): For
    (const auto& elem:coll) {
        cout << elem.first.data () <& Lt ":" << elem.second << Endl
    }
}
Iv. Associative Arrays

Just go ahead and get the code:

int main ()
{
    unordered_map<string, double> coll;
    coll["A"] = 0.1;
    coll["B"] = 0.2;
    coll["Pi"] = 3.1415926;
    coll["Money" = -99.9;

    for (auto Iter:coll)
        cout << iter.first.data () << ":" << iter.second << Endl;
}

This code is like a python dictionary. The [] operator here is used to extract the first element in the pair inside the map, and if that element exists, it is directly assigned, and if it does not exist, then the assignment is added.

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.