7

2 つの STL マップがstd::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};あり、std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};

bar が foo のサブセットであるかどうかを調べたい。

要素はマップでソートされているため、foo の bar から最初の要素を見つけて、その場所から foo の bar から連続する要素を見つけると思います。

ここでの問題は、cpp の STL マップでそれを行う方法を理解できないことです。マップ内のある場所からマップの最後まで検索するたびに、マップ内の検索範囲を狭めることはできますか?

問題を説明したことを願っています。

4

3 に答える 3

9

std::includesキーのみを比較するカスタム コンパレータでアルゴリズムを使用します。

#include <map>
#include <algorithm>
#include <iostream>

int main()
{
    std::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};
    std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};
    typedef std::pair<int,int> pair;

    std::cout <<
       std::includes(foo.begin(), foo.end(), bar.begin(), bar.end(),
           [](const pair& p1, const pair& p2)
           {
               return p1.first < p2.first;
           });
}
于 2013-04-16T19:30:07.247 に答える
2

簡単な方法は、Boost.Rangeを以下と組み合わせて使用​​することboost::includesです。

using namespace boost::adaptors;
bool result = includes(foo | map_keys, bar | map_keys);

最小限の完全なプログラムは次のようになります (マップされた値は無視されます)。

#include <map>
#include <iostream>
#include <boost/range.hpp>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>

int main()
{
    std::map<int, int> foo = {{1, 0}, {2, 0}, {3, 0}, {4, 0}, {5, 0}, {6, 0}};
    std::map<int, int> bar = {{2, 0}, {4, 0}, {5, 0}};

    using namespace boost::adaptors;
    std::cout << includes(foo | map_keys, bar | map_keys);
}

これが実際のです。

于 2013-04-16T19:18:56.320 に答える