'테크 > CodeSignal-C++' 카테고리의 다른 글
6. Browsing system for Deque (0) | 2024.11.30 |
---|---|
5. Map using custom object key (0) | 2024.11.29 |
4. Multimap to Map (0) | 2024.11.28 |
3. Map & Multimap (0) | 2024.11.26 |
2. Queue and Deque (0) | 2024.11.23 |
6. Browsing system for Deque (0) | 2024.11.30 |
---|---|
5. Map using custom object key (0) | 2024.11.29 |
4. Multimap to Map (0) | 2024.11.28 |
3. Map & Multimap (0) | 2024.11.26 |
2. Queue and Deque (0) | 2024.11.23 |
1. Browsing system 알고리즘 원리
2. Deque의 주요 함수 (push_back, push_front, pop_back, pop_front, front, back)
With what you've learned about deques, it's time to apply your knowledge to create a more advanced data structure — a BrowserHistory management system. This system will enable users to visit new URLs, navigate backward and forward through their browsing history, and efficiently manage these operations using deques to handle past and future navigations. Your challenge is to implement the three methods that drive this functionality:
void visit(const std::string& url) — Adds a new URL to the browsing history and clears any forward history.
std::string back(int steps) — Moves back in history by the specified number of steps, if possible, and updates the forward history. Returns the current URL after the update.
std::string forward(int steps) — Moves forward in history by the specified number of steps, if possible, and updates the current browsing history. Returns the current URL after the update.
Example:
visit("codesignal.com") - Visits codesignal.com; current history: ["codesignal.com"].
visit("learn.codesignal.com") - Visits learn.codesignal.com; current history: ["codesignal.com", "learn.codesignal.com"].
visit("learn.codesignal.com/course-paths") - Visits learn.codesignal.com/course-paths; current history: ["codesignal.com", "learn.codesignal.com", "learn.codesignal.com/course-paths"].
back(2) - Moves back 2 steps; current history: ["codesignal.com"]. Returns codesignal.com.
forward(1) - Moves forward 1 step; current history: ["codesignal.com", "learn.codesignal.com"]. Returns learn.codesignal.com.
#include "solution.hpp"
#include <algorithm>
void BrowserHistory::visit(const std::string &url) {
// TODO: Add the visited URL to the history and clear the future
history_.push_back(url);
future_.clear();
}
std::string BrowserHistory::back(int steps) {
// TODO: Move the specified number of steps back in the history, if possible, and update the future accordingly
// std::rotate(history_.rbegin(), history_.rbegin()+steps, history_.rend());
// Return the current URL after updating
if (history_.empty()) {
return "No back";
}
for (int index = 0; index < steps; ++index) {
std::string current = history_.back();
future_.push_front(current);
history_.pop_back();
if (history_.empty()) {
return "No back";
}
}
return history_.front();
}
std::string BrowserHistory::forward(int steps) {
// TODO: Move the specified number of steps forward in the history, if possible, and update the history accordingly
// Return the current URL after updating
if (future_.empty()) {
return "No back";
}
for (int index = 0; index < steps; ++index) {
std::string current = future_.front();
history_.push_back(current);
future_.pop_back();
if (future_.empty()) {
return "No back";
}
}
return history_.back();
}
int main() {
BrowserHistory browser;
// TODO: Use the BrowserHistory class to simulate visiting some URLs, then going back and forward in the history, printing the resulting URL after each move
browser.visit("codesignal.com");
browser.visit("learn.codesignal.com");
browser.visit("learn.codesignal.com/course-paths");
std::cout << browser.back(2) << std::endl;
std::cout << browser.forward(1) << std::endl;
return 0;
}
7. CodeSignal Course Certificate Advanced Built-In Data Structures and their Usage in C++ (0) | 2024.12.01 |
---|---|
5. Map using custom object key (0) | 2024.11.29 |
4. Multimap to Map (0) | 2024.11.28 |
3. Map & Multimap (0) | 2024.11.26 |
2. Queue and Deque (0) | 2024.11.23 |
1. operator< 오버로딩
전역으로는 두 객체를 받아 비교하지만 클래스 내부에서는 첫 번째 멤버는 this로 고정이므로 하나의 매개변수를 받는다.
2. 범위형 반복문에서 객체를 const로 선언한다면 getter도 const 선언이 되어야 한다.
3. 비교 연산이 < 일 경우 오름차순, > 일 경우 내림차순이다. STD 컨테이너는 기본적으로 오름차순이다.
In this exercise, you will implement a small inventory management system using C++ with Product objects as keys in a std::map. Each Product should have an id (integer) and a name (string). The std::map should automatically sort Product objects by their id using custom sorting logic by overloading the < operator.
Here's what you need to accomplish:
Define the Product class: Include id and name attributes, and overload < to enable sorting by id.
Create and populate the inventory: Define a std::map<Product, int> named inventory where the key is a Product and the value is the stock quantity. Add several Product objects with different id and name values and their respective stock quantities.
Implement product search: Write a findProductById function to search for a Product by id in the inventory. It should find the first product with an id not less than the specified search value and return its name and stock quantity. If no match is found, return a message indicating that the product was not found.
Display the result: Use findProductById to find and print a product by id without removing it from the map.
This task combines object-oriented programming with sorted data structures in C++, focusing on custom sorting and efficient map search. Follow the steps and structure your code accordingly.
#include "solution.hpp"
// TODO: Define a Product class with attributes id (integer) and name (string).
// Implement operator< for sorting by id.
class Product {
private:
int id;
std::string name;
public:
Product(int id, std::string name) {
this->id = id;
this->name = name;
}
bool operator<(const Product& other) const {
return this->id < other.id;
}
int getId() const {
return this->id;
}
std::string getName() const {
return this->name;
}
};
std::string findProductById(const std::map<Product, int>& inventory, int id) {
std::string result;
for (const auto& pair : inventory) {
if (pair.first.getId() >= id) {
result = pair.first.getName() + ", " + std::to_string(pair.second);
}
}
if (result.empty()) {
return "The product was not found";
} else {
return result;
}
}
int main() {
// TODO: Create an instance of std::map named inventory.
std::map<Product, int> inventory;
// TODO: Add some Product objects to inventory with different ids and names,
// associating each Product with an integer stock quantity.
inventory.insert(std::make_pair(Product(1, "Ice"), 5));
inventory.insert(std::make_pair(Product(2, "Cream"), 3));
inventory.insert(std::make_pair(Product(3, "Cookie"), 7));
inventory.insert(std::make_pair(Product(6, "Snack"), 4));
// TODO: Implement and use a function to find the first Product object with
// an id not less than a specified value, then print it without removing.
std::cout << findProductById(inventory, 5) << std::endl;
return 0;
}
7. CodeSignal Course Certificate Advanced Built-In Data Structures and their Usage in C++ (0) | 2024.12.01 |
---|---|
6. Browsing system for Deque (0) | 2024.11.30 |
4. Multimap to Map (0) | 2024.11.28 |
3. Map & Multimap (0) | 2024.11.26 |
2. Queue and Deque (0) | 2024.11.23 |
1. return {};
요즘 Modern C++의 추세.
초기화된 객체를 반환.
반환 타입에 따라 빈 컨테이너, 기본값, 기본 생성자 호출이 이뤄짐
2. .find()는 기본적으로 iterator를 반환하며 iterator는 기본적으로 const
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;
}
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 |