简体   繁体   中英

Boost multi_index unqiue index issue

I'm trying to create a URL managing object using boost::multi_index. It has 2 indexes, one indexes position of each path item and one indexes key to find that item.

class InternalPath
  {
  public:
    struct PathItem
    {
      int Position;
      std::string Key;
      std::string Path;
    };

    typedef boost::multi_index_container<
      PathItem,
      boost::multi_index::indexed_by<
        boost::multi_index::ordered_unique<boost::multi_index::member<PathItem,int,&PathItem::Position>>,
        boost::multi_index::ordered_unique<boost::multi_index::member<PathItem,std::string,&PathItem::Key>>
      >
    > PathContainer;

  private:
    PathContainer path_;
};

However there is a problem that not all items would have it's key. Most items would only consist of Position and Path. I want key to be unique. Now the problem would come when I insert more than one non key item.

Is it possible to allow key with empty string to have more than one item in the container. If not what should I do to overcome this problem?

A slightly more elegant solution using Boost.Variant:

struct PathItem
{
  PathItem(int p,const std::string& k,const std::string& pt):
    Position(p),Key(k),Path(pt){}

  PathItem(int p,const std::string& pt):
    Position(p),Key(p),Path(pt){}

  int Position;
  boost::variant<int,std::string> Key;
  std::string Path;
};

Short answer is you can't do that. As a quick workaround, consider providing some unique string when no key is present, for instance some special character that prevents collision with real keys followed by the position (which is assumed to be unique, right?):

struct PathItem
{
  PathItem(int p,const std::string& k,const std::string& pt):
    Position(p),Key(k),Path(pt){}

  PathItem(int p,const std::string& pt):
    Position(p),Key("!"),Path(pt){Key+=p;}

  int Position;
  std::string Key;
  std::string Path;
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM