0

Hello guys,

I want to use structure as a map key , is it possible? Or is there any work around in c++ to do this or am i doing something wrong?

I was trying to do this.

#include <iostream>
#include <map>
#include<stdint.h>
#include "stdio.h"

using namespace std;

struct PdpNetworkLocalKey
{

    PdpNetworkLocalKey(uint32_t a, bool b)
    {
      ip = a;
      isLocal = b;
    }
    PdpNetworkLocalKey()
    {
      ip = 0;
      isLocal = 0;
    }
    uint32_t ip;
    bool isLocal;
};

int main()
{
    PdpNetworkLocalKey x1(10, false);
    PdpNetworkLocalKey x2(10, true);
  
 // x1.ip = 10; x1.isLocal = false;
  //x2.ip = 10; x2.isLocal = true;

  PdpNetworkLocalKey searchKey;
  searchKey.ip = 10;
  searchKey.isLocal = false;

  map <PdpNetworkLocalKey, uint32_t> Ip_Key_Int_Map;
  Ip_Key_Int_Map.insert(map <PdpNetworkLocalKey, uint32_t>:: value_type(x1 , 1000));
  Ip_Key_Int_Map.insert(map <PdpNetworkLocalKey, uint32_t>:: value_type(x2 , 2000));

  map <PdpNetworkLocalKey, uint32_t>::iterator it; 
  it = Ip_Key_Int_Map.find(searchKey);
  if (it != Ip_Key_Int_Map.end())
  {
   uint32_t z =  (*it).second;
    printf("searched value is %u\n", z);
  }
return 0;
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Narue
0

Provided you supply either an overloaded operator<, or a comparison predicate in the map constructor, you can use any user-defined type as the key.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.