#include <iostream>
#include <vector>
#include <map>
#include <string>
int main() {
// key value
std::map<std::string, int> student;
std::map<int, std::vector<std::string>> sd;
std::string ip;
int inp;
// Taking input for 5 students
for(int i = 0; i < 5; i++) {
std::cin >> ip >> inp;
student[ip] = inp; // Insert directly into the map
}
// Output the map content
for(const auto& i : student) {
std::cout << i.first << ' ' << i.second << std::endl;
sd[i.second].push_back(i.first); // Use a vector to handle multiple students with the same marks
}
std::cout << std::endl;
// Output the map content (marks to student names)
for(const auto& i : sd) {
std::cout << i.first << ": "; // Print the mark (key)
for(const auto& name : i.second) {
std::cout << name << " "; // Print all student names with this mark
}
std::cout << std::endl;
}
return 0;
}
/*
Yes, in C++, the std::map is designed to store unique keys (not necessarily unique values) and automatically sorts these keys in
ascending order (by default). Here’s how this works in terms of keys and values:
Keys in a std::map must be unique. If you try to insert a pair with a key that already exists, the new value will replace the old
value associated with that key.
Values in a std::map do not have to be unique. Multiple keys can map to the same value, but each key must remain unique.
For example, in the map std::map<std::string, int>, the student names (keys) must be unique, but multiple students can have the
same marks (values). The map will automatically sort by student names (keys) because std::map is sorted by key by default.
*/
To embed this project on your website, copy the following code and paste it into your website's HTML: