【问题标题】:Is there a data structure that allows storing more than two elements? [duplicate]是否有允许存储两个以上元素的数据结构? [复制]
【发布时间】:2021-09-14 00:08:15
【问题描述】:

所以,我正在搜索的内容可能看起来像这样(没有xxx):

const xxx<std::string, std::string, void (*)(std::string)> commands = {
  {"exit", "Exit Program", f1},
  {"test", "Start Test", f2},
  {"help, h", "Help Screen", f3}
};

据我所知,列表、向量、地图等无法做到这一点。有什么可以替换xxx 的吗?或者有其他简单的方法吗?

【问题讨论】:

  • 看起来你想要一个std::tuple
  • 我认为 std::tuple 在这里工作完美,但感谢您的想法。

标签: c++ list data-structures


【解决方案1】:

在基本级别上,您可以使用std::tuple: std::tuple&lt;std::string, std::string, std::function&lt;void(std::string)&gt; command,它可以容纳任意数量的类型。

如果您想要多个,请使用std::vector&lt;std::tuple&lt;...&gt;&gt;

using Command = std::tuple<std::string, std::string, std::function<void(std::string)>>;
using CommandList = std::vector<Command>;

CommandList commands;

对于更高级的组合,自定义的用户定义类型更容易,但对于只有三种类型,它并不值得。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-11
    相关资源
    最近更新 更多