Home > database >  C - Automatically insert a pair-like object into a map?
C - Automatically insert a pair-like object into a map?

Time:07-26

Lets say we have some pair like class:

class PairLike{
public:
   string key;
   int val;
   PairLike(string Key, int Val) : key(Key), val(Val){};

   
   //...other members
};

A few objects to go along with it:

PairLike p1("a",1);
PairLike p2("b",2);
PairLike p3("c",3);
PairLike p4("d",4);

Is there a way of automatically working with this object? For example, something similar to:

std::map<PairLike> container = {p1,p2,p3};
container.insert(p4);

Instead of writing something like:

std::map<string, int> container = {{p1.key, p1.val}, {p2.key, p2.val}, ... }
container.insert({p4.key, p4.val})

I'm aware that using an std::set<PairLike> with a comparator using is_transparentcan achieve the result I'm looking for. However, I am curious if there is any way to approach this problem with a map.

CodePudding user response:

That is not possible. std::pair is defined as part of the class definition, and cannot be altered to a custom class.

P.S. As noted by @UnholySheep, it's defined in the CPP standard:

namespace std {
  template<class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key, T>>>
  class map {
  public:
    // types
    using key_type               = Key;
    using mapped_type            = T;
    using value_type             = pair<const Key, T>;
    ...

CodePudding user response:

You could provide a conversion operator for converting to std::pair:

class PairLike{
public:
   // ...

   operator std::pair<const std::string, int>() {
       return {key, val};
   }
};

And use it like:

std::map<string, int> container{p1,p2,p3};
container.insert(p4);
  •  Tags:  
  • c
  • Related