[C++] mapとpair

C++

map

ヘッダーのインクルード

#include <iostream>
#include <map>

作成

std::map<int, std::string> map;

要素の追加

map[1] = "one";
map[2] = "two";
map[3] = "three";

要素にアクセス

std::cout << "Key 2 has value: " << map[2] << std::endl;

ループで処理

for(const auto& pair : map) {
    std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}

存在確認

// 存在するとき
if(map.find(3) != map.end()) {
    std::cout << "Key 3 exists in the map!" << std::endl;
}

// 存在しないとき
if(map.find(4) == map.end()) {
    std::cout << "Key 4 does not exist in the map!" << std::endl;
}

特定の位置にイテレータを使って挿入

std::map<int, std::string> m;
m[5] = "five";
m[8] = "eight";

// キー5の前にキー3を挿入
m.insert(m.find(5), {3, "three"});

valueでソート

std::vector を使用してソート

std::map<int, std::string> m;
m[1] = "one";
m[3] = "three";
m[2] = "two";

std::vector<std::pair<int, std::string>> vec(m.begin(), m.end());

std::sort(vec.begin(), vec.end(), 
         [](const std::pair<int, std::string>& a, const std::pair<int, std::string>& b) {
             return a.second < b.second;
         });

for(const auto& p : vec) {
    std::cout << p.first << " => " << p.second << std::endl;
}

std::multimap を使用してソート

std::map<int, std::string> m;
m[1] = "one";
m[3] = "three";
m[2] = "two";

std::multimap<std::string, int> sortedMap;
for(const auto& p : m) {
    sortedMap.insert({p.second, p.first});
}

for(const auto& p : sortedMap) {
    std::cout << p.second << " => " << p.first << std::endl;
}

pair

定義

std::pair<int, std::string> p;

初期化

std::pair<int, std::string> p1(1, "one");

auto p2 = std::make_pair(2, "two");

vector

insert

// 新しい要素
std::pair<int, std::string> newElement = std::make_pair(42, "NewValue");

// インデックス2の位置に新しい要素を挿入する
vec.insert(vec.begin() + 2, newElement);
C++
シェアする
cloraをフォローする
スポンサーリンク
プログラミングな日常
タイトルとURLをコピーしました