8

私はそのような方法で std::map を使用しています:

#include <map>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    map<string, int> my_map;

    my_map.insert(pair<string, int>("Ab", 1));
    my_map.insert(pair<string, int>("Abb", 2));
    my_map.insert(pair<string, int>("Abc", 3));
    my_map.insert(pair<string, int>("Abd", 4));
    my_map.insert(pair<string, int>("Ac", 5));
    my_map.insert(pair<string, int>("Ad", 5));

    cout<<my_map.lower_bound("Ab")->second<<endl;
    cout<<my_map.upper_bound("Ab")->second<<endl;
    return 0;
}

http://ideone.com/5YPQmj

キーが特定の文字列 ("Ab" など) で始まるすべての値を取得したいと考えています。map::lower_bound を使用して開始イテレータを簡単に取得できます。しかし、どうすれば上限を取得できますか? セット全体を下限から繰り返して、すべてのキーがまだ「Ab」で始まっているかどうかを確認する必要がありますか?

4

3 に答える 3

1

このページをチェックして、同様の回答を見つけました:(複雑な検索操作をマップする

コード実行:

template<typename Map> typename Map::const_iterator
find_prefix(Map const& map, typename Map::key_type const& key)
{
    typename Map::const_iterator it = map.upper_bound(key);
    while (it != map.begin())
    {
        --it;
        if(key.substr(0, it->first.size()) == it->first)
            return it;
    }

    return map.end(); // map contains no prefix
}

この例では、特定の部分文字列を探し始めるまで、upper_bound から逆方向に繰り返し処理しているように見えます。

この例は少し異なりますが、優れた構成要素として提供する必要があります

于 2013-04-28T13:38:16.500 に答える
1

述語 (どの値を含めるかを示す bool 関数) を指定したときに、通常のイテレーターから「開始」イテレーターと「終了」イテレーターを提供するブースト フィルター イテレーターを使用できます。

例えば:

template <class Predicate>
boost::filter_iterator<Predicate, map<string,int>::const_iterator> begin(Predicate predicate) const
{
    return boost::make_filter_iterator(predicate, my_map.begin(), my_map.end());
}
template <class Predicate>
boost::filter_iterator<Predicate, map<string,int>::const_iterator> end(Predicate predicate) const
{
    return boost::make_filter_iterator(predicate, my_map.end(), my_map.end());
}

struct isMatch
{
    isMatch(const std::string prefix) {m_prefix = prefix;};
    bool operator()(std::string value)
    {
        return value.find_first_of(m_prefix) == 0;
    };
    std::string m_prefix;
};

//using:
isMatch startWithAb("Ab");
auto myBegin = boost::filter_iterator<startWithAb> begin();
auto myEnd = boost::filter_iterator<startWithAb> end();
于 2013-04-28T14:13:20.353 に答える