๐ C++ STL - map ์ ๋ฆฌ
โ
map ๊ธฐ๋ณธ ์ฌ์ฉ๋ฒ
#include <map> // ํค๋ํ์ผ ํฌํจํด์ผ ์ฌ์ฉ ๊ฐ๋ฅ
int main() {
std::map<int, int> mapInt;
mapInt.insert(std::make_pair(1, 100)); // ๊ฐ๋ฅ (pair ๊ฐ์ฒด ์ฌ์ฉ)
for (std::map<int, int>::iterator iter = mapInt.begin(); iter != mapInt.end(); ++iter) {
std::cout << iter->first << " : " << iter->second << std::endl;
}
}map์ pair ๊ฐ์ฒด๋ฅผ ์์๋ก ๊ฐ์ง๋ฏ๋ก,(*iter).first,(*iter).second๋๋iter->first,iter->second๋ก ์ ๊ทผํด์ผ ํจ.map์ ์๋์ ๋ ฌ์ ์ง์ํ๊ธฐ ๋๋ฌธ์ ์ ๋ ฌ ๋ฐฉ์์ ๋ํ์กฐ๊ฑด์๋ฅผ ์ ์ธ์์ ๋ฃ์ ์ ์์.
โ
map ์์ ์ถ๊ฐ ๋ฐฉ๋ฒ
1๏ธโฃ pair ๊ฐ์ฒด๋ฅผ ์ง์ ์์ฑํ์ฌ ์ถ๊ฐ
std::pair<int, int> MyPair(1, 100);
mapInt.insert(MyPair);2๏ธโฃ pair ์์ ๊ฐ์ฒด ์ฌ์ฉ
mapInt.insert(std::pair<int, int>(2, 200));3๏ธโฃ make_pair ํจ์ ์ฌ์ฉ (์ถ์ฒ)
mapInt.insert(std::make_pair(3, 300));4๏ธโฃ value_type ์ฌ์ฉ
std::map<int, int>::value_type MyValue(4, 400);
mapInt.insert(MyValue);5๏ธโฃ value_type ์์ ๊ฐ์ฒด ์ฌ์ฉ
mapInt.insert(std::map<int, int>::value_type(5, 500));6๏ธโฃ [] ์ฐ์ฐ์ ์ฌ์ฉ (์ฃผ์!)
mapInt[6] = 600;insert์ ์ฐจ์ด์ insert๋ ์ค๋ณต๋ ํค๊ฐ ์์ผ๋ฉด ์ถ๊ฐ๋์ง ์์.[]์ฐ์ฐ์๋ ํค๊ฐ ์กด์ฌํ๋ฉด ๊ธฐ์กด ๊ฐ์ ๋ฎ์ด์.
7๏ธโฃ ๋ชจ๋ C++ (C++11 ์ด์)
๐น ์ ๋ํผ ์ด๊ธฐํ ์ฌ์ฉ
mapInt.insert({7, 700});๐น emplace ์ฌ์ฉ (์ถ์ฒ)
mapInt.emplace(8, 800);insert๋pair๊ฐ์ฒด๋ฅผ ๋จผ์ ์์ฑํ ํ ์ฝ์ ,emplace๋ ์ง์ ์์ฑํ์ฌ ๋ ํจ์จ์ ์.
โ
map์ ๋ฐ๋ณต์
- ์๋ฐฉํฅ ๋ฐ๋ณต์ ์ง์ (
++,--๊ฐ๋ฅ)
std::map<int, int>::iterator iter = mapInt.begin();
iter++;
iter++;
iter--;
mapInt.insert({10, 1000}); // ์๋ ์ ๋ ฌ๋๋ฏ๋ก ์ค๊ฐ ์ฝ์
์ ์๋ฏธ ์์
mapInt.erase(iter); // ํน์ ์์น์ ์์ ์ญ์
mapInt.erase(4); // key ๊ฐ์ผ๋ก ์ญ์ ๊ฐ๋ฅโ
map๊ณผ find_if
#include <iostream>
#include <map>
#include <cstring>
#include <algorithm>
struct tagFinder {
tagFinder(const char* pTag) : m_pTag(pTag) {}
template<typename T>
bool operator()(const T& MyPair) const {
return !strcmp(m_pTag, MyPair.first);
}
const char* m_pTag;
};
int main() {
std::map<const char*, int, bool(*)(const char*, const char*)> myMap(
[](const char* a, const char* b) { return strcmp(a, b) < 0; }
);
myMap.insert({"aaa", 100});
myMap.insert({"bbb", 200});
myMap.insert({"ccc", 300});
// ์ผ๋ฐ find (์ฃผ์ ๋น๊ต๋ก ์ธํด ๋น์ ์์ ์ธ ๊ฒฐ๊ณผ ๊ฐ๋ฅ)
auto iter = myMap.find("bbb");
// find_if๋ฅผ ์ฌ์ฉํ ๋ฌธ์์ด ๋น๊ต
iter = std::find_if(myMap.begin(), myMap.end(), tagFinder("bbb"));
if (iter != myMap.end()) {
std::cout << "์ฐพ์ ๊ฐ: " << iter->second << std::endl;
} else {
std::cout << "์ฐพ์ง ๋ชปํจ\n";
}
return 0;
}๐จ map<const char*, int>์ ๋ฌธ์ ์
const char*์ ํค๋ก ์ฌ์ฉํ๋ฉด ์ฃผ์ ๊ฐ์ผ๋ก ๋น๊ตํ๋ฏ๋ก"bbb"๋ฅผ ์ ๋๋ก ์ฐพ์ง ๋ชปํ ์๋ ์์.- ํด๊ฒฐ๋ฒ:
std::string์ ํค๋ก ์ฌ์ฉ (๊ถ์ฅ)strcmp๋ฅผ ์ด์ฉํ ๋น๊ต์ ์ถ๊ฐ
โ
map์ ์ ๋ ฌ ๋ฐฉ์
| Key ํ์ | ์ ๋ ฌ ๊ธฐ์ค |
|---|---|
char | O (ASCII ์ฝ๋ ์์๋๋ก ์ ๋ ฌ) |
char* | X (์ฃผ์ ๊ฐ ๊ธฐ์ค ์ ๋ ฌ) |
string | O (operator<๊ฐ ์ํ๋ฒณ ๊ธฐ์ค ์ ๋ ฌ) |
๐ ์ ๋ฆฌ: map์ ์ฌ์ฉํ ๋ const char*๋ณด๋ค std::string์ ์ฐ๋ ๊ฒ์ด ์์ ํจ!