Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > searching keys in std::map using map::upper_bound

Reply
Thread Tools

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

 
 
Erik Arner
Guest
Posts: n/a
 
      11-02-2004

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

 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Google search result to be URL-limited when searching site, but notwhen searching Web stumblng.tumblr Javascript 1 02-04-2008 09:01 AM
How to link foreign keys & primary keys using python? Harry George Python 9 06-13-2006 06:29 AM
serial keys/validation keys sandeep Kanwal C++ 1 10-29-2004 06:36 PM
In search of elegant code - searching keys of hashes in array David Filmer Perl Misc 8 12-14-2003 04:47 PM
keyboard keys replacing mouse keys? larry Computer Support 8 09-14-2003 07:32 PM



Advertisments