searching keys in std::map using map::upper_bound

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Erik Arner

    #1

    searching keys in std::map using map::upper_bound


    Hi,

    let's say I have a std::map<std::s tring,int> and I want to search the map
    for all keys that start with "foo". The regexp equivalent is to search for
    "foo*", or perhaps "^foo*".

    At present I do this quick'n'dirty by appending a tilde (~) to the query
    term, since I know it's last in the ascii table and my keys don't include
    any special characters. So to find everything that starts with "foo" I
    search the map from map::lower_boun d("foo") to map::upper_boun d("foo~").
    See below for complete program that demonstrates this.

    There must be a much smarter, cleaner, more portable and less ugly way to
    do this. Any ideas?

    Thanks,
    Erik

    Code:


    #include <iostream>
    #include <map>

    using namespace std;

    int main(int argc, char* argv[])
    {

    map<string, int> testmap;


    testmap.insert( make_pair("fon" , 1) );
    testmap.insert( make_pair("foo" , 2) );
    testmap.insert( make_pair("foob ar", 3) );
    testmap.insert( make_pair("fool ", 4) );
    testmap.insert( make_pair("fop" , 5) );

    map<string, int>::iterator start_it = testmap.lower_b ound("foo");
    map<string, int>::iterator stop_it = testmap.upper_b ound("foo~");

    for( ; start_it != stop_it; ++start_it ) {
    cerr<<(*start_i t).first<<'\t'< <(*start_it).se cond<<endl;
    }

    return 0;
    }


    --
    My Hotmail address is a spam magnet. If replying by email, use
    erik dot arner at cgb dot ki dot se

Working...