简体   繁体   English

std :: pair中有超过2个变量

[英]More than 2 variables in std::pair

pair looks like this 对看起来像这样

std::vector<std::pair<uint64 /*id*/, std::string /*message*/>

and if i want 3 variables in vector ? 如果我要向量中的3个变量? Can i use pair or what ? 我可以使用一对还是什么?

Thanks 谢谢

If I have understood correctly you could use std::tuple declared in header <tuple> . 如果我正确理解,则可以使用标头<tuple>声明的std::tuple For example 例如

std::vector<std::tuple<uint64, std::string, SomeOtherType>> v;

In C++ sometimes I find quite useful to define trivial all-public data-only classes like 在C ++中,有时我发现定义琐碎的仅公开数据类非常有用,例如

struct Event {
    unit32 id;
    std::string msg;
    uint32 time;
    Event() : id(0), msg(""), time(0) {} // If needed
    Event(uint32 id, const std::string& msg, uint32 time)
      : id(id), msg(msg), time(time) {}
};

Surely a bit of typing, but IMO way better than having to use e.second or std::get<1>(e) instead of e.msg everywhere in the code. 当然可以键入一些内容,但是IMO的方式比必须在代码中的各处使用e.secondstd::get<1>(e)而不是e.msg

Writing is done once, reading many times. 写作一次,多次阅读。 Saving writing time at the expense of increasing reading/understanding time is a Very Bad Idea. 以增加阅读/理解时间为代价来节省写作时间是一个非常糟糕的主意。

If you don't want C++11, you can use 如果您不想要C ++ 11,则可以使用

std::pair<uint64, std::pair<std::string, SomeOtherType> >

But this is as wrong as trying to put three values to a pair . 但这和尝试将三个值放入一一样错误。 Why I consider it wrong? 为什么我认为这是错误的? A pair means two values. 表示两个值。 If you put three or any other number of values in a pair , you are doing something like this . 如果将三个或任何其他数量的值成对放置,则表示您正在执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 试图使std :: make_pair接受两个以上的参数 - Trying to make std::make_pair take more than 2 arguments 为什么std :: optional <int>的构造比std :: pair <int,bool>更昂贵? - Why is the construction of std::optional<int> more expensive than a std::pair<int, bool>? 如何将std :: pair视为两个独立的变量? - How to treat std::pair as two separate variables? 为什么 std::pair 公开成员变量? - Why does std::pair expose member variables? 为什么 std::pair 的分配和排序比 std::vector 快? - Why allocation and sort of std::pair is faster than std::vector? 返回2元组的效率不如std :: pair吗? - Is returning a 2-tuple less efficient than std::pair? std :: pair分配语义命名变量的第一个和第二个 - std::pair assigning first and second to semantically named variables 为什么`std :: pair`将`std :: tuple`作为ctor参数类型而不是`const std :: tuple&`? - Why does `std::pair` take `std::tuple` as ctor argument type rather than `const std::tuple&`? 我的哪种情况会std :: map <A,B> 比排序的std :: vector更快 <std::pair<A,B> &gt;? - I which situation will std::map<A,B> be faster than sorted std::vector<std::pair<A,B>>? 覆盖std :: locale上的多个方面 - Override more than one facet on std::locale
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM