471,571 Members | 2,662 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,571 software developers and data experts.

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


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?


#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

Jul 22 '05 #1
0 1733

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

3 posts views Thread by hivie | last post: by
2 posts views Thread by repairman2003 | last post: by
5 posts views Thread by Fred Zwarts | last post: by
3 posts views Thread by could.net | last post: by
1 post views Thread by benhoefer | last post: by
3 posts views Thread by Henrik Goldman | last post: by
12 posts views Thread by mohitanchlia | last post: by
reply views Thread by XIAOLAOHU | last post: by
reply views Thread by Vinnie | last post: by
reply views Thread by lumer26 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.