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

Discussion in 'C++' started by Erik Arner, Nov 2, 2004.

  1. Erik Arner

    Erik Arner Guest

    Hi,

    let's say I have a std::map<std::string,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_bound("foo") to map::upper_bound("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("foobar", 3) );
    testmap.insert( make_pair("fool", 4) );
    testmap.insert( make_pair("fop", 5) );

    map<string, int>::iterator start_it = testmap.lower_bound("foo");
    map<string, int>::iterator stop_it = testmap.upper_bound("foo~");

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

    return 0;
    }


    --
    My Hotmail address is a spam magnet. If replying by email, use
    erik dot arner at cgb dot ki dot se
     
    Erik Arner, Nov 2, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. asdf

    std::set::upper_bound

    asdf, Apr 12, 2006, in forum: C++
    Replies:
    3
    Views:
    368
    Mark P
    Apr 13, 2006
  2. asdf

    std::set::upper_bound

    asdf, Apr 12, 2006, in forum: C++
    Replies:
    0
    Views:
    296
  3. Fred Zwarts
    Replies:
    5
    Views:
    1,547
    Andrew Koenig
    Apr 23, 2006
  4. Diego Martins

    stl map, lower_bound and upper_bound

    Diego Martins, Aug 14, 2006, in forum: C++
    Replies:
    3
    Views:
    1,181
    Diego Martins
    Aug 15, 2006
  5. Henrik Goldman

    Problem with map upper_bound

    Henrik Goldman, Jul 5, 2007, in forum: C++
    Replies:
    3
    Views:
    386
    James Kanze
    Jul 6, 2007
Loading...

Share This Page