首页 > 解决方案 > 具有自定义 value_type 的 C++ 映射

问题描述

对于 astd::map<K, V>默认value_type值为std::pair<const K, V>. 有没有办法使用自定义value_type?据我所知,你不能。

编辑:要清楚,自定义value_type可能是这样的:

struct Edge {
  K from;
  V to;

  int calculate_thing();
  void print_debug();
};

例如,假设我有一些我不想像这样更改的现有功能:

template<typename It>
void processEdges(It begin, It end) {
   for(auto it = begin; it != end; ++it) {
     do_stuff(it->from);
     do_more_stuff(it->calculate_thing());
  }
}

标签: c++dictionary

解决方案


总是这样std::pair<const K, V>,你无法改变。

如果您需要 custom value_type,也许您可​​以使用std::set(最好使用透明的 comaprator)。


推荐阅读