c++ - std::map::size_type 对于 std::map 其 value_type 是它自己的 size_type

标签 c++ c++11 stl stdmap size-type

我有一个 std::map<std::pair<std::string, std::string>, float>这占用了太多内存,为了使用更少的内存,我决定将唯一字符串映射到整数(例如 std::map<std::string, int> ,其中每个新的唯一字符串都映射到 map 的当前 size() ),并将这些整数值用作映射的成对键(例如,std::map<std::pair<int, int>, float>)。

而不是 int , 我想用 std::map::size_type :

using map_index = std::map::size_type;
std::pair<map_index, map_index> key;

当然,这不会编译,因为我需要为 map 提供参数列表:

vector.cc:14:19: error: invalid use of template-name `std::map' without an argument list
 using map_index = std::map::size_type;

这(理论上)是我想要实现的目标:

using map_index = std::map<std::string, map_index>::size_type;

它给出了以下(预期的)编译器错误:

vector.cc:15:41: error: `map_index' was not declared in this scope
 using map_index = std::map<std::string, map_index>::size_type;

让编译器推断出正确的 value_type 的正确方法是什么?对于 std::map谁的value_type是自己的size_type

最佳答案

size_t 应该足以应对这种情况。

但如果你坚持,你可以这样做:

#include <type_traits>
#include <map>

template <class Key, class Value = size_t, size_t depth = 0, class = void>
struct GetSizeType {
    using type = typename GetSizeType<Key, typename std::map<Key, Value>::size_type, depth + 1>::type;
};

template <class Key, class Value, size_t depth>
struct GetSizeType<Key, Value, depth, std::enable_if_t<std::is_same_v<Value, typename std::map<Key, Value>::size_type>>> {
    using type = typename std::map<Key, Value>::size_type;
};

template <class Key, class Value>
struct GetSizeType<Key, Value, 100, void> {};

int main() {
    using X = GetSizeType<int>::type;

    return 0;
}

它将在 GetSizeType 上递归运行,递归调用将在

  • 达到递归调用深度限制(在这种情况下将没有成员type),或者
  • 找到 std::map 的特化,其中 mapped_typesize_type 相同(成员 type 别名 size_type)。

关于c++ - std::map::size_type 对于 std::map 其 value_type 是它自己的 size_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431281/

相关文章:

C++程序在询问数组大小后崩溃

c++ - 二叉搜索树根正在工作,但它不能有任何 child ?

c++ - 非可变 lambda 函数 : are copy-captured variables allowed to be const?

c++ - 混合 C++11 std::thread 和 C 系统线程(即 pthreads)

c++ - 为什么 std::vector 没有释放方法?

c++ - ID 字段在自定义点类中间歇性丢失

c++ - 如何找到两个不同数组中交换的值?

c++ - 交错 std::map 插入和迭代

c++ - ./lib/gcc/x86_64-linux-gnu/4.6/libstdc++.a 的用法是什么

c++ - 如何使用 const_iterator 公开 C++ 类