我有一个 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_type
和size_type
相同(成员type
别名size_type
)。
关于c++ - std::map::size_type 对于 std::map 其 value_type 是它自己的 size_type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431281/