C++のstd::mapから値を持つすべての一致するキーを検索します
この投稿では、C++のマップから値を持つすべての一致するキーを見つける方法について説明します。
1.ループの使用
簡単な解決策は、イテレーターベースのforループを使用して、マップ内のすべてのマッピングを反復処理し、指定されたターゲットと一致する値をフィルター処理することです。これは、C++では次のように実装できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <string> #include <map> #include <vector> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; for (auto it = map.begin(); it != map.end(); it++) { if (it->second == target) { keys.push_back(it->first); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
出力:
2
4
C++ 17以降では、範囲ベースのforループ内で構造化バインディングを使用できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <algorithm> #include <map> #include <vector> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; for (auto const &[key, val] : map) { if (val == target) { keys.push_back(key); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
出力:
2
4
2.使用する BOOST_FOREACH
The BOOST_FOREACH
イテレータまたは述語を直接処理することを回避することにより、C++ループを単純化します。たとえば、次のプログラムは BOOST_FOREACH
マップの内容をループし、指定された値に一致するすべてのキーを取得します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> #include <string> #include <map> #include <vector> #include <boost/foreach.hpp> int main() { std::map<int, char> map = { {1, 'A'}, {2, 'B'}, {3, 'C'}, {4, 'B'} }; char target = 'B'; std::vector<int> keys; std::pair<int, char> entry; BOOST_FOREACH(entry, map) { if (entry.second == target) { keys.push_back(entry.first); } } for (const auto &key: keys) { std::cout << key << std::endl; } return 0; } |
出力:
2
4
これで、C++のマップから値を持つすべての一致するキーを見つけることができます。
こちらも参照: