c++ - 如何拥有具有不同类型值的 map ?

标签 c++

<分区>

我需要一个以 int 作为键和值的映射,它可以是各种类型的对象

std::map<int, differenttypes*> mapping;

并像这样提取对象:

 dialog* newDialog = mapping[let]; //let is some int

像这样插入该值:

 mapping[let] = newDialog2;

我如何用 map 做到这一点?例如,不同类型采用字符串、整数等。 也许使用 boost::variant?

最佳答案

您可以使用 union 和“类型标签”(枚举或字符串)来指示 union 实际包含的内容。假设您要保存字符串、整数和 float :

union valU { float f; int i; char *s; };
enum valE { fl, in, st };
struct variousT { valU val; valE type; };

void print(variousT v)
{
   switch(v.type)
   {
      case fl: printf("%f", v.val.f); break;
      case in:  printf("%d", v.val.i); break;      
      case st:  printf("%s", v.val.s); break;
   }
}

当然 print 可以是一个成员函数,variousT 中应该有重载的 setter 将标签和值等一起设置。但这是原始机制。

关于c++ - 如何拥有具有不同类型值的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36461976/

相关文章:

c++ - 如何使用指针数组反转数据(解析二进制文件)

c++ - "Expected ' } ' at end of input"。为什么我不断收到此错误?

c++ - 如何通过按 Escape 键重置 QLineEdit 文本?

c++ - 如何初始化静态类的疙瘩成语的d(指针)?

c++ - 支持 MSVC++2017 的 `auto&&`

c++ - 如何使用 VS Code 在弹出的控制台窗口中运行程序?

c++ - C++11 中的 (Di|Tri) 图

c++ - 在C++中将int转换为char时 "narrowing"如何工作?

c++ - 解释 Valgrind 输出以找出数据竞争的位置

c++ - 错误 : ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function