Point
1. return {};
요즘 Modern C++의 추세.
초기화된 객체를 반환.
반환 타입에 따라 빈 컨테이너, 기본값, 기본 생성자 호출이 이뤄짐
2. .find()는 기본적으로 iterator를 반환하며 iterator는 기본적으로 const
Problem
Your journey with std::multimap in C++ has equipped you with the skills to manipulate and traverse multiple key-value pairs efficiently. It's time to apply this knowledge! Imagine you're keeping track of participants' scores in a riveting quiz competition. Your task is to create a std::multimap in C++ to record these scores, possibly with multiple entries per participant. Then, write a function that aggregates all scores for each participant into a std::map, where each participant maps to a vector of scores they received. Your goal is to transform this multimap into a map, encapsulating all scores in a single vector for each participant.
For example, given the input multimap:
Copy to clipboard
{
{"Olivia", 85},
{"Liam", 92},
{"Emma", 95},
{"Noah", 90},
{"Olivia", 88},
{"Liam", 75},
{"Emma", 89}
}
The output map should be:
Copy to clipboard
{
{"Olivia", [85, 88]},
{"Liam", [92, 75]},
{"Emma", [95, 89]},
{"Noah", [90]}
}
Embark on this challenge and effectively utilize std::multimap and std::map!
#include "solution.hpp"
std::map<std::string, std::vector<int>> aggregateScores(const std::multimap<std::string, int>& scores) {
// TODO: Implement the aggregateScores function which takes a multimap of participant names (string) to scores (int)
// and returns a map where each participant maps to a vector of their scores.
std::map<std::string, std::vector<int>> map;
for (const auto& score : scores) {
// IsExist?
auto it = map.find(score.first);
if (it != map.end()) {
// Exist
it->second.push_back(score.second);
} else {
// Not Exist
std::vector<int> number;
number.push_back(score.second);
map.emplace(std::make_pair(score.first, number));
}
}
//return {};
return map;
}
int main() {
std::multimap<std::string, int> participantScores = {
{"Olivia", 85},
{"Liam", 92},
{"Emma", 95},
{"Noah", 90},
{"Olivia", 88},
{"Liam", 75},
{"Emma", 89}
};
std::map<std::string, std::vector<int>> aggregatedScores = aggregateScores(participantScores);
for (const auto& entry : aggregatedScores) {
std::cout << "Participant: " << entry.first << " - Scores: ";
for (int score : entry.second) {
std::cout << score << " ";
}
std::cout << std::endl;
}
return 0;
}
'테크 > CodeSignal-C++' 카테고리의 다른 글
6. Browsing system for Deque (0) | 2024.11.30 |
---|---|
5. Map using custom object key (0) | 2024.11.29 |
3. Map & Multimap (0) | 2024.11.26 |
2. Queue and Deque (0) | 2024.11.23 |
1. Stack (0) | 2024.11.23 |