在C ++中使用std :: map键

时间:2010-04-10 13:27:28

标签: c++ stl map key

我需要在C ++中创建两个不同的地图。 Key的类型为CHAR*,Value是指向struct的指针。我在不同的迭代中用这些对填充2个映射。在创建两个映射之后,我需要找到所有这样的实例,其中CHAR*引用的字符串的值是相同的。

为此,我使用以下代码:

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运算符只是等于指针的内存地址。

我的问题是,如何更改此类键的equals运算符,或者我可以为字符串使用不同的数据类型?

2 个答案:

答案 0 :(得分: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
}

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

根据您的用例,您不必必须存储指向结构的指针:

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

最后一点说明:typedef结构的方式是C-ism,在C ++中,以下就足够了:

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

答案 1 :(得分: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;
}