2010-04-10 98 views
1

我有一个要求,用C++创建两个不同的地图。密钥的类型是CHAR*,Value是指向结构体的指针。我用这些对填充2个地图,分别进行迭代。在创建两个映射之后,我需要找到所有这样的实例,其中CHAR*引用的字符串的值是相同的。在C++中std :: map键

对于这个我使用下面的代码:

typedef struct _STRUCTTYPE 
{ 
.. 
} STRUCTTYPE, *PSTRUCTTYPE; 

typedef pair <CHAR *,PSTRUCTTYPE> kvpair; 

.. 

CHAR *xyz; 

PSTRUCTTYPE abc; 

// after filling the information; 

Map.insert (kvpair(xyz,abc)); 


// the above is repeated x times for the first map, and y times for the second map. 
// after both are filled out; 

std::map<CHAR *, PSTRUCTTYPE>::iterator Iter,findIter; 

for (Iter=iteratedMap->begin();Iter!=iteratedMap->end();mapIterator++) 
{ 
    char *key = Iter->first; 

    printf("%s\n",key); 

    findIter=otherMap->find(key); 

    //printf("%u",findIter->second); 

    if (findIter!=otherMap->end()) 
    { 
    printf("Match!\n"); 
    } 
} 

上面的代码并没有表现出任何的比赛,虽然在这两种地图键列表表现出明显的匹配。我的理解是CHAR *的equals运算符只是指针的内存地址。

我的问题是,我应该怎么做来改变这种类型的键的等号运算符,或者我可以使用不同的数据类型的字符串?

+0

我不想编辑它,因为它可能会转换成社区Wiki,但如果你使用1010101模式的按钮(就像KennyTM为你做的那样),代码将会格式化尖括号将正确显示。 – 2010-04-10 13:54:00

回答

4

我的理解是CHAR *的equals运算符只是指针的内存地址。

你的理解是正确的。

最简单的事情就是使用std::string作为关键。这样,你得到了比较实际的字符串值不费力的工作:

std::map<std::string, PSTRUCTTYPE> m; 
PSTRUCTTYPE s = bar(); 
m.insert(std::make_pair("foo", s)); 

if(m.find("foo") != m.end()) { 
    // works now 
} 

注意,如果你并不总是手动删除它们,你可能会泄漏内存为您的结构。如果您无法按价值进行存储,请考虑使用智能指针。根据您的用例

,你不必neccessarily存储指向的结构:

std::map<std::string, STRUCTTYPE> m; 
m.insert(std::make_pair("foo", STRUCTTYPE(whatever))); 

最后请注意:typedef ING结构你正在做的方式是C-主义,在C++以下就足够了:

typedef struct STRUCTTYPE { 
    // ... 
} *PSTRUCTTYPE; 
+0

其实我的代码使用sprintf()很多,所以我不得不改变这些事件。一旦我做出这些改变,我会尽快回复你。谢谢无论如何:) – Soumava 2010-04-10 13:55:00

+0

我做了sprintf并获得了字符串中的char *键,然后做了std :: string key1 = key; 现在似乎工作。 :) 谢谢。 – Soumava 2010-04-10 14:10:23

+2

有关PSTRUCTTYPE的说明 - typedefing隐藏了事实是指针的事实被很多人认为是不好的风格。 – 2010-04-10 14:16:01

0

如果使用std::string而不是char *,那么可以使用更方便的比较函数。此外,您可以使用STL set_intersection算法(请参阅here以了解更多详细信息)来查找两个已排序容器中的共享元素(std::map当然已排序),而不是编写自己的密钥匹配代码。这里是一个例子

typedef map<std::string, STRUCTTYPE *> ExampleMap; 
ExampleMap inputMap1, inputMap2, matchedMap; 

// Insert elements to input maps 
inputMap1.insert(...); 

// Put common elements of inputMap1 and inputMap2 into matchedMap 
std::set_intersection(inputMap1.begin(), inputMap1.end(), inputMap2.begin(), inputMap2.end(), matchedMap.begin()); 

for(ExampleMap::iterator iter = matchedMap.begin(); iter != matchedMap.end(); ++iter) 
{ 
    // Do things with matched elements 
    std::cout << iter->first << endl; 
} 
+0

这是一个非常有用的功能..切断了很多代码。谢谢。 – Soumava 2010-04-11 13:43:26