-
Keys of a map
Hey guys
This is a really simple little question. I have a map that looks like this
map <char *, bool> Accepts
And later I have a loop that reads words in from a long string and puts them into the map like such:
Accepts[(char *)StringFound] = true;
But I'm having problems. It seems the values I assign to the map arent the strings I expect to assign. Is there a way I can cout a list of all the keys?
Sorry to waste anyones time on whats probably a very trivial matter.
-
Dont use pointers.....there's the problem that char* arrays need special functions for comparison, and there's always a danger that the pointer will be out of scope if you arent carefull
Do this;
std::map <std::string, bool> Accepts
Far better
-
Alright then thanks Fordy, I should have thought of that. But do you have any idea how I can list all the values?
-
Code:
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
typedef std::map <std::string, bool> MyMap;
void Print(const MyMap::value_type& p)
{
std::cout << p.first << " = ";
std::cout << (p.second ? "true" : "false") << std::endl;
}
int main()
{
MyMap Accepts;
Accepts["foo"] = true;
Accepts["bar"] = false;
Accepts["whatever"] = true;
std::for_each(Accepts.begin(),Accepts.end(),Print);
}
-
Thanks Fordy, as always you've been nothing but helpful. I had to modify it a bit to get it to print to a file and to use the classes I already have, but I got it.
Turns out that the value I'd been testing for (text/html) was the one value that was never passed to the program, when it should have been.