맵과 조회
Coddy의 Rust 개발자를 위한 C++ 코스 레슨. 48개 중 14번째.
Rust의 HashMap에는 정렬된 순서가 없습니다. BTreeMap은 std::map의 키 순서와 더 비슷합니다. C++의 std::map은 키를 정렬합니다. 아래 첨자로 접근하면 키가 없을 때 기본값이 삽입됩니다. find와 count는 삽입하지 않고 조회합니다.
Rust
fn main() {
use std::collections::HashMap;
let counts = HashMap::from([("pens", 0)]);
println!("{}", counts.contains_key("pens"));
println!("{}", counts.get("pads").copied().unwrap_or(0));
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
int main(){
std::map<std::string,int> m{{"oak",4}};std::cout<<m.count("elm")<<" "<<m.size()<<"\n";
}
각 프로그램을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 공백으로 구분된 단어들입니다. 사전순으로 정렬된 단어 빈도를 word:count 형식으로 반환하고, 각 항목은 공백으로 구분하세요. 단어가 없으면 빈 값을 반환하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 수정할 수 있으며, 공개 시그니처는 유지하세요. 수정할 수 없는 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작을 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 부호 있는 int 범위에 들어가며, 별도 언급이 없으면 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);std::vector<std::string>v;std::string w;while(in>>w)v.push_back(w);std::cout<<frequencies(v)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Rust 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러