【问题标题】:How can i get data from std::map type struct?如何从 std::map 类型结构中获取数据?
【发布时间】:2016-05-06 08:18:59
【问题描述】:

首先非常感谢您帮助我并阅读这篇文章。

我有这个结构:x,y。 我有一张地图,其中数据就是那个结构。 例如,我想从 iterator [1] get .x 获取数据。 我该怎么做?

非常感谢。

【问题讨论】:

    标签: dictionary iterator std


    【解决方案1】:

    如果您有一个迭代器it 指向std::map<X, Y> 的元素,那么您可以使用it->first 获得对键的常量引用,并使用it->second 获得对映射类型的引用,因为it指向 std::map<X, Y>::value_type 类型的值

    std::pair<std::map<X, Y>::key_type const,
              std::map<X, Y>::mapped_type>
    

    例如:

    Y * setX(std::map<X, X> & dict, X const & value) {
        std::map<X, Y>::iterator it = dict.find(value);
        if (it != dict.end())
            return nullptr;
        assert(it->first == value);
        return &it->second;
    }
    

    【讨论】:

      【解决方案2】:
      #include <map>
      #include <iostream>
      #include <string>
      using namespace std;
      
      
      int main()
      {
          // for a simple struct you could use "pair" (especially if you don't want to name it).
          // anyway:
          map<int, pair<double, string>> mymap;
          mymap[0] = pair<double, string>(4.56, "hello");
          mymap[1] = pair<double, string>(9.87, "hi");
          for(auto & item : mymap)
          {
              cout << "Key: " << item.first << ", Value: [" << item.second.first << ", " << item.second.second << "]" << endl;
          }
          return 0;
      }
      

      输出:

      键:0,值:[4.56,你好]

      键:1,值:[9.87,hi]

      【讨论】:

        猜你喜欢
        • 2016-03-27
        • 2012-04-06
        • 2018-11-19
        • 2019-12-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 1970-01-01
        相关资源
        最近更新 更多