Menu
CoddyTech

맵과 조회

Coddy의 PHP 개발자를 위한 C++ 코스 레슨. 48개 중 14번째.

PHP 연관 배열은 키를 삽입 순서대로 유지합니다. 존재하지 않는 키를 읽으면 "Undefined array key" 경고가 발생하고 null이 반환됩니다. 반면 isset, array_key_exists, ??는 배열을 변경하지 않고 키를 조회합니다. C++의 std::map은 키를 정렬된 상태로 유지하므로 순회는 가장 작은 키에서 시작합니다. 첨자 연산은 읽기 전용이 아닙니다. 존재하지 않는 키에 m[key]를 사용하면 기본값으로 해당 키가 삽입됩니다. 삽입하지 않고 조회해야 한다면 find 또는 count를 사용하세요.

PHP

<?php
$counts = ["pens" => 0, "ink" => 2];
$counts["clips"] = 5;
echo $counts["pads"] ?? 0, " ", count($counts), "\n";
echo implode(",", array_keys($counts)), "\n";

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{{"pens",0},{"ink",2}};
m["clips"]=5;
std::cout<<m.count("pads")<<" "<<m.size()<<" ";
std::cout<<m["pads"]<<" "<<m.size()<<"\n";
std::cout<<m.begin()->first<<"\n";
}

각 프로그램을 독립적으로 추적해 보세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 설명하며, 원본과 대상의 출력이 같다고 가정하지 않습니다.

challenge icon

챌린지

쉬움

입력: 공백으로 구분된 단어들입니다. 사전순으로 정렬한 단어별 빈도를 word:count 형식으로 공백을 사이에 두고 반환하거나, 비어 있는 경우 빈 문자열을 반환하세요.

exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있습니다. 공개 시그니처는 그대로 유지하세요. 잠긴 main.cpp는 stdin을 읽고 API를 직접 호출합니다. 또한 명시된 경우 공개 API 동작도 독립적으로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력과 결과는 signed 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";
}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

PHP 개발자를 위한 C++의 모든 레슨

직접 연습해 보세요: 온라인 C++ 컴파일러