0 / 0 / 0
Регистрация: 07.04.2019
Сообщений: 26
1

Не могу разобраться с stl в частности с map;

25.04.2019, 19:53. Показов 1098. Ответов 4
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Есть map<myClass, int, sort_name> eleaments;
При добавлении в контейнер новых элементов бинарное дерево строится из результата сравнения поля name у двух объектов ключа. Как мне заново отсортировать этот контейнер но только по другому полю объектов ключа?
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
25.04.2019, 19:53
Ответы с готовыми решениями:

Не могу разобраться с map(STL)
Недавно понадобилось использование ассоциативного массива map(STL), дабы сократить код программы....

Не могу разобраться как обновить в std::map<std::string, вектор_структур>
Не могу разобраться как обновить вектор структур после его добавления в map без удаления и...

stl map
где можно прочитать о stl map? подскажите книги..

Map stl
Не могу понять, почему не находит через h1.find(argv). когда argv == &quot;-o&quot; vs пишет &quot;itr =...

4
330 / 145 / 56
Регистрация: 17.10.2015
Сообщений: 580
25.04.2019, 20:02 2
Developer_222, код в студию.
0
0 / 0 / 0
Регистрация: 07.04.2019
Сообщений: 26
25.04.2019, 20:07  [ТС] 3
Employee.h
C++
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
#pragma once
#include<iostream>
#include<string>
 
using namespace std;
 
class Employee
{
private:
    string name;
    string  position;
    int salary;
public:
    
    string getName() const;
    string getPosition() const;
    int getSalary() const;
    
    void print_Emp();
    
 
 
    void setName(string);
    void setPosition(string);
    void setSalary(int);
 
    Employee(string, string, int);
    
    ~Employee();
};



Employee.cpp
C++
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include "Employee.h"
 
 
 
 
 
string Employee::getName() const
{
    return name;
}
 
string Employee::getPosition() const
{
    return position;
}
 
int Employee::getSalary() const
{
    return salary;
}
 
void Employee::print_Emp()
{
    cout << "Имя: " << this->name << endl;
    cout << "Должность: " << this->position << endl;
    cout << "Заработная плата: " << this->salary << endl;
}
 
 
 
void Employee::setName(string name)
{
    this->name = name;
}
 
void Employee::setPosition(string position)
{
    this->position  = position;
}
 
void Employee::setSalary(int salary)
{
    this->salary = salary;
}
 
Employee::Employee(string name, string position, int salary)
{
    this->name = name;
    this->position = position;
    this->salary = salary;
}
 
 
 
 
 
Employee::~Employee()
{
}



Source.cpp
C++
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include<iostream>
#include "Employee.h"
#include<string>
#include<algorithm>
#include<vector>
#include<list>
#include <map>
 
using namespace std;
 
/*struct sort_name {
    bool& operator()(const Employee & first, const Employee & second)
    {
        return first.getName() < second.getName;
    };
};
*/
 
struct name_Emp {
 
    bool operator()(Employee str, Employee str1) 
    {
        return str.getName() < str1.getName();
 
    }
};
 
struct sorted_position{
    bool operator()(const Employee & first, const Employee & second)
    {
        return first.getPosition() < second.getPosition();
    }
};
 
 
int main() 
{
    setlocale(LC_ALL, "ru");
 
    
    map<Employee, int,name_Emp> map_Emp;
    Employee newEmp1("Bob", "Director", 100000), newEmp2("Charlee", "Helper", 50000), newEmp3("Kevin", "CEO", 400000), newEmp4("Alex", "it", 150000);
    map_Emp.emplace(newEmp1,21);
    map_Emp.emplace(newEmp2, 31);
    map_Emp.emplace(newEmp3,1);
    map_Emp.emplace(newEmp4,10);
 
    auto it = map_Emp.begin();
 
 
    for (auto it : map_Emp)
    {
        cout << it.second << endl;
    };
 
 
    
    sort(it,map_Emp.end(), );
    
    
    
    /*
    vector<Employee> first;
    Employee newEmp1("Bob", "Director", 100000), newEmp2("Charlee", "Helper", 50000), newEmp3("Kevin", "CEO", 400000), newEmp4("Alex", "it", 150000);
    first.push_back(newEmp1);
    first.push_back(newEmp2);
    first.push_back(newEmp3);
    first.push_back(newEmp4);
 
    auto it = first.begin();
    auto it2 = first.end();
    
    for (auto it : first) 
    {
        it.print_Emp();
        cout << endl;
    };
    cout << endl << endl;
    
    sort(it,it2,sort_of_name);
 
    for (auto it : first)
    {
        it.print_Emp();
        cout << endl;
    };
    
    
    vector<Employee> second_vect;
    second_vect = first;
    for (auto it : second_vect)
    {
        it.print_Emp();
        cout << endl;
    };
    */
    /*
    list<Employee> list_Emp;
    Employee new_Emp1("Megan","Developer", 400000), new_Emp2("Sindy", "Helper", 100000), new_Emp3("Billy", "Emp", 120000), new_Emp4("Math", "Deve",300000);
 
    list_Emp.push_back(new_Emp1);
    list_Emp.push_back(new_Emp2);
    list_Emp.push_back(new_Emp3);
    list_Emp.push_back(new_Emp4);
 
    for (auto obj : list_Emp) 
    {
        obj.print_Emp();
        cout << endl;
    };
 
    list_Emp.sort(sort_of_name);
    
    cout << endl << endl;
 
    for (auto obj : list_Emp)
    {
        obj.print_Emp();
        cout << endl;
    };
    */
 
 
 
    system("pause");
    return 0;
}
0
Комп_Оратор)
Эксперт по математике/физике
8949 / 4703 / 629
Регистрация: 04.12.2011
Сообщений: 13,999
Записей в блоге: 16
25.04.2019, 20:13 4
Лучший ответ Сообщение было отмечено Developer_222 как решение

Решение

Цитата Сообщение от Developer_222 Посмотреть сообщение
Как мне заново отсортировать этот контейнер но только по другому полю
Developer_222, что значит
Цитата Сообщение от Developer_222 Посмотреть сообщение
но только по другому полю объектов ключа?
?
Developer_222, так может спросить лишь человек который отсортировал по "старому" полю. Но вы же не сортировали. Сортировал map. И заставить тот контейнер который уже создан пересортировать что-либо нельзя. Не гуманно это. Создайте новый map такой же, но с перламутровыми пуговицами с другим предикатом.
1
2782 / 1935 / 570
Регистрация: 05.06.2014
Сообщений: 5,600
25.04.2019, 20:15 5
Цитата Сообщение от Developer_222 Посмотреть сообщение
Как мне заново отсортировать этот контейнер но только по другому полю объектов ключа?
Никак. Нужно больше контейнеров.
C++
1
2
3
4
5
6
7
8
9
10
11
int main()
{
    std::map<std::string,MyClass> baseIndex;
    std::map<int,MyClass*> intIndex;
    std::map<double,MyClass*> doubleIndex;
 
    baseIndex["key"]=MyClass();
    intIndex[1]=&baseIndex["key"];
    doubleIndex[1.234]=&baseIndex["key"];
    return 0;
}
1
25.04.2019, 20:15
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
25.04.2019, 20:15
Помогаю со студенческими работами здесь

STL :: map
Столкнулся с такой проблемой: Нужно вставить в отсортированную map-таблицу элемент. Использую:...

STL map
Вопрос:как мне узнать что не создавался map с заданым str? #include &lt;iostream&gt; #inlclude &lt;map&gt;...

Вопрос об map STL
Как вивести map? list&lt;int&gt; l; for (int i=1; i&lt;=5; i++) l.push_back(i); map&lt;int,list&lt;int&gt;&gt;...

Сложение двух STL map
Напишите пожалуйста простой пример сложения двух STL map


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
5
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru