C++ unordered_map using a custom class type as the key

前端 未结 4 1058
梦如初夏
梦如初夏 2020-11-21 23:32

I am trying to use a custom class as key for an unordered_map, like the following:

#include 
#include 
#include         


        
4条回答
  •  攒了一身酷
    2020-11-22 00:18

    Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

    // UnorderedMapObjectAsKey.cpp
    
    #include 
    #include 
    #include 
    
    struct Pos
    {
      int row;
      int col;
    
      Pos() { }
      Pos(int row, int col)
      {
        this->row = row;
        this->col = col;
      }
    
      bool operator==(const Pos& otherPos) const
      {
        if (this->row == otherPos.row && this->col == otherPos.col) return true;
        else return false;
      }
    
      struct HashFunction
      {
        size_t operator()(const Pos& pos) const
        {
          size_t rowHash = std::hash()(pos.row);
          size_t colHash = std::hash()(pos.col) << 1;
          return rowHash ^ colHash;
        }
      };
    };
    
    int main(void)
    {
      std::unordered_map umap;
    
      // at row 1, col 2, set value to 5
      umap[Pos(1, 2)] = 5;
    
      // at row 3, col 4, set value to 10
      umap[Pos(3, 4)] = 10;
    
      // print the umap
      std::cout << "\n";
      for (auto& element : umap)
      {
        std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
      }
      std::cout << "\n";
    
      return 0;
    }
    

提交回复
热议问题