STL containers: map. Part 7

class map c ++, stl containers, map for beginnersWe have considered a simple example of using map<>, but the use of such a container is already much more complicated sequence container. Container map<> (table, display):

  • It contains ordered pairs <key,value>, where the key and value may belong to arbitrary types. For key type must be either a predetermined, or user-defined comparison operation;

  • Elements with any key value should be unique;

  • Attempting to add (method insert()) to table a new pair with an existing key value end failure;

  • The operation of adding a new pair in the table returns pair type <iterator, bool>, in which the second component (logical second) points to the success of the operation. If it true, the first component of the return value (first) iterator gives an added item. If he false, returns iterator existing item with the same key;

  • Table indexing operations ( [ ] or at() ) require any type of value as the key, certain key;

  • Indexing operation at(), when setting the parameter key, Absence in the table elements, causes an exception;

  • In front of, indexing operation [ ], when setting the parameter key, Absence in the table elements, the exception does not cause. (conversely, even if the indexation requested read-only, adds the container a new element with the desired key value, but null field values);

These definitions may seem intricate, but it would explain the subsequent example.

Before presenting the example, we have to prepare some test data files to work with associative containers. The work is a voluminous character data demonstrates the power of using STL tables. As we prepare text data files, containing English-language original texts of several poems of Lewis Carroll.

Not a bit more complicated to use and Russian texts, but in this case you have to work with wstring classes and localized transformations, it will only increase the bulkiness of examples without an increase in their meaningfulness.

I've given you a few texts of different lengths for a thorough testing of the code and subsequent parts of the presentation (files shown with counting the number of strings of the texts). Here, for example, Humpty-Dumpty.txt - is the text of part VI Humpty-Dumpty «Alice in Wonderland».

30 Brother_And_Sister11 Humpty-Dumpty34 Jabberwock

A Jabberwock.txt - is the text of part VI Humpty-Dumpty «Alice in Wonderland" - known in the Russian-language version of the poem (by VS Vysotsky): About Fear Barmaglota, a son! He Svirn and wild…

In our original (Copyright, English-speaking, to debug – file Jabberwock.txt) This text looks like:

JabberwockTwas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the Borogove,
And the mome raths outgrabe.

«Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!» …

Text, certainly, syntactically complex, making it an excellent material for debugging applications. You are provided with excellent materials for further independent experiments!

So ... our app will calculate the number of occurrences of each of the letters of the alphabet in the proposed text, using map<>:

Container map<> - Not the best option for your goals: in finding new letters in the text we will try to add it as a key table, but if the character is already present in the table, the attempt fails. In this case, after failures, we, the index key, simply increment the number of its occurrences. And that's what we may learn:

class map c ++, stl containers, map for beginners
class map c ++, stl containers, map for beginners
class map c ++, stl containers, map for beginners

Notice how increased size of the table after, how it was indexing [ ] Implemented search (reading!) missing keys (‘q’, 'from', ‘x’).

The question arises: Why do you see as size() values ​​such as the 44, 47, 50, 52, If we observe only the layout for repeatability 26 characters from 'a’ to ' z '? The answer is simple: because space characters may be included in the text, punctuation, uppercase letters, we do not observe in issuing test.

If you take advantage of this new opportunity to C ++ 11 standard, as the initialization lists, the creation and initialization of the table may look much easier:

Naturally, All this will be compiled only if you specify the compiler options for the use of C ++ 11 standard:class map c ++, stl containers, map for beginners

From the above it should be clear, that any type can be used as a search key in a table, provided always, for him or there is a natural comparison operation (int, float, string, …), or we ourselves define a user-defined function, which will be used for comparisons. A few ways to do this are listed below:

here we, replacing key comparison function, change the sort order of items when you place them in the table. (In the 2nd embodiment, a functional object, functor, work which will be discussed in a separate part of our review.)

class map c ++, stl containers, map for beginners

Newsletter of programming:

STL containers: map. Part 7
Rate this article

About Olej

practical experience about software development 40 years. Teacher Global Logic international software company. IBM Developer Works Permanent author of publications. Scientific editor of the computer literature publishing house "Symbol-Plus", St. Petersburg.

8 thoughts on “STL containers: map. Part 7

  1. The result is an interesting and understandable article.
    And to be continued – removal, replacement, contains, search key and others.?

  2. Thank you for the incredible work and help in learning C ++, but now went unclear. Until now it was normal during lessons. Before writing something exemplary, to explain it. Otherwise, if the sample is not clear, then there is no sense of learning, Only practice memorized and assimilated. OK unnamed ^ Z (ctrl-Z) Can not see in the picture the result of the work program with the verses in the console and well, if the reader knows, that it means the end of the file for the console, without entering the program would not work (cycle not completed). But in the following example, went even harder .

    1) functors have not been studied, it is not known and an example is impossible to understand, because it says bool operator(), and so we did not once, after the operator of the word before the brackets always written sign operator (+, -, …). Good, you might think, that probably means that the sign, that is after expression in return. And even more incomprehensible in the following strings:

    2) map< int, int, less > – what's this? It has been studied that map consists of key-value pairs, and less doing here and what is less generally do not understand. In appearance it can be assumed that it is a template class with parameter int. But most likely it indicates the sort order for the key value in ascending or descending order of data in the container map.

    3) map mg1(great); – it is unclear. You can guess in one direction or another, only guesses are of little help in such cases. mg1(great) – a constructor function with a parameter? This designer has not been studied for the map, and not only to map.

    4) map – about the same.

    In summary, What is this third option emerged when declaring object container map inside the angle brackets? It can be seen in context, he sets the sort order by key value, but there is no reliable information.

      1. Until now it was normal during lessons. Before writing something exemplary, to explain it.

        1. Just “still” was only because, that until now it was only flowers – addressed only the most-the most basic concepts of C ++. Now described is already advanced enough funds.

        2. From matlingvistika, theory of programming languages ​​known, what any programming language can not strictly be described series, and therefore they are described by recursively: using design, who have not been previously described. This theory.
        If there is something you absolutely do not understand – miss this, you will return to it later, at “2-m aisle”, when it has become clear.

Leave a Reply

Your email address will not be published. Required fields are marked *