We 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, causesan 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_Sister | 11 Humpty-Dumpty | 34 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:
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<>:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | #include <iostream> #include <sstream> #include <map> using namespace std; int main(int argc, char **argv) { map< char, int > alphabet; while (cin) { string line; getline(cin, line); if (line.empty()) continue; istringstream ist(line); // строка как поток чтения char let; while ((let = ist.get()) && let != EOF) { // посимвольно pair< map< char, int >::iterator, bool > ret; ret = alphabet.insert(pair< char, int >(let, 1)); // если неудача - буква уже присутствует: if (!ret.second) ret.first->second++; } } cout << "alphabet size = " << alphabet.size() << endl; // если буква найдена - вывести её: for (char c = 'a'; c <= 'z'; c++) { cout << c << "("; try { cout << alphabet.at(c); } catch (exception const& e) { cout << '-'; } cout << ") "; } cout << endl; cout << "alphabet size = " << alphabet.size() << endl; for (char c = 'a'; c <= 'z'; c++) { cout << c << "(" << alphabet[c] << ") "; } cout << endl; cout << "alphabet size = " << alphabet.size() << endl; } |
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:
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:
1 2 3 4 5 6 7 8 9 10 11 12 | #include <iostream> #include <map> using namespace std; int main(int argc, char **argv) { map< int, char > nums = { { 1, 'a' },{ 3, 'b' },{ 5, 'c' },{ 7, 'd' } }; for (auto i = nums.begin(); i != nums.end(); i++) cout << i->first << "->" << i->second << " "; cout << endl; } |
Naturally, All this will be compiled only if you specify the compiler options for the use of C ++ 11 standard:
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | #include <iostream> #include <map> using namespace std; template< typename Map > void print_map(Map& m) { cout << "{ "; for (auto& p : m) // перебор всей таблицы cout << p.first << ':' << p.second << ' '; cout << "}" << endl; } // функция сравнения: bool great(int lhs, int rhs) { return lhs > rhs; } // функтор сравнения: struct classcomp { bool operator()(const int& lhs, const int& rhs) const { return lhs > rhs; } }; int main(int argc, char **argv) { // таблица, сравнение по умолчанию map< int, int, less< int > > ml = { { 1, 2 },{ 2, 3 },{ 3, 4 },{ 4, 5 } }; print_map(ml); // таблица с нашей great() функцией сравнения map< int, int, bool(*)(int, int) > mg1(great); mg1.insert(ml.begin(), ml.end()); print_map(mg1); // таблица с классом-функтором map< int, int, classcomp > mg3(ml.begin(), ml.end()); print_map(mg3); } |
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.)
The result is an interesting and understandable article.
And to be continued – removal, replacement, contains, search key and others.?
Necessarily will.
This is what part of? 7-I?
So there is already ready 16.
expect.
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.
2) map< int, int, less >
3) map mg1(great);
code is displayed in the comments do not fully. Pity.
Kind of figured out the benefit of the Internet at your fingertips.
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.