Re: map problem
On 26 Mar, 20:36, csaba.tru...@gmail.com wrote:
My first response was the same: char*'s will be compared as pointers.
Using Visual Studio 2008 I ran the following code, which as far as I
see reconstructs the OP's problem.
#include <map>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
map<char*, vector<char*> > data;
data["foo"] = vector<char*>();
data["foo"].push_back("foo.bar");
data["foo"].push_back("foo.baz");
data["bar"] = vector<char*>();
data["bar"].push_back("bar.bar");
data["bar"].push_back("bar.baz");
if (data.find("foo") == data.end())
cout << "not found" << endl;
else
cout << "found" << endl;
}
Strangely enough the output is "found". Anyone has an explanation?
String literals with the same contents like "foo" and "foo" are
basically the same objects (thay have the same address). This is true
for probably all modern compilers, don't know if it is true in C++
standard. So using them as keys like in your example should work.
If you would use pointers pointing to some buffer on stack or heap
it wouldn't generally work or it would behave not as it should.
For example;
std::map<char*, int> map_of_int;
char key[512];
while (std::cin >> key)
map_of_int[key] = 0;
if (map_of_int.find("foo") != map_of_int.end())
std::cout << "found" << std::endl;
else
std::cout << "not found" << std::endl;
This piece of code will always print "not found", even
if string "foo" will be read into key buffer.
Cheers
Sfider
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]