Словарь (map)

Словарь состоит из пар значений «ключ»-«значение». Например, «apple»-«яблоко». Набор ключей уникален, упорядочен, чтобы обеспечить быстрый доступ.

Словари часто используются, когда нужно организовать доступ к элементам коллекции по другому полю. Например, у вас приложение – адресная книга. В ней нужно по имени человека получить его контактную информацию. Контактная информация – какой-то класс. Доступ к контактам планируется только по имени. Тогда можно данные как-то так: map <string, ContactInformation>.

Идея за словарем: вместо индекса, по которому мы обращаемся к данным в массиве, использовать другой тип, чтобы обращаться к элементам массива.

 

Пример

#include "stdafx.h"

#include <set>

#include <iostream>

#include <algorithm>

#include <iterator>

#include <string>

#include <map>

#include <sstream>

 

using namespace std;

 

struct ContactInformation

{

string FirstName;

int Age;

string Address;

string Phone;

 

ContactInformation(

const string& firstName,

int age,

const string& address,

const string& phone) : FirstName(firstName), Age(age), Address(address), Phone(phone)

{

 

}

 

ContactInformation() // Required by map to return elements

: FirstName("Unknown"), Age(5), Address("Unknown"), Phone("23232323")

{

 

}

 

string ToString() const

{

stringstream stream;

 

stream << "First name: " << FirstName << "; Age: " << Age << "; Address: " << Address << "; Phone: " << Phone << ".";

 

return stream.str();

}

};

 

map<string, ContactInformation> CreateContacts()

{

map<string, ContactInformation> contacts;

 

contacts["Barbara"] = ContactInformation("Barbara", 13, "Ivanovo", "22323");

contacts["Ahmed"] = ContactInformation("Ahmed", 40, "Istanbul", "44333");

 

return contacts;

}

 

void PrintContacts(const map<string, ContactInformation>& contacts)

{

cout << "Contacts\n";

for (auto contactIterator = contacts.begin(); contactIterator != contacts.end(); ++contactIterator)

{

cout << "Key: " << contactIterator->first << endl;

cout << "Information: " << contactIterator->second.ToString() << endl;

}

// Second more better approach

for (const auto &contactPair: contacts)

{

cout << "Key: " << contactPair.first << endl;

cout << "Information: " << contactPair.second.ToString() << endl;

}

}

 

int _tmain(int argc, _TCHAR* argv[])

{

map<string, ContactInformation> contacts = CreateContacts();

 

// add

PrintContacts(contacts);

 

// check if key exists

if (contacts.count("Barbara") == 1) // check if element exists

cout << "Barbara exists\n";

 

// delete

contacts.erase("Barbara");

 

// modify

contacts["Ahmed"].Address = "USA";

 

PrintContacts(contacts);

 

getchar();

 

return 0;

}