What is std::pair?

前端 未结 10 1725
面向向阳花
面向向阳花 2020-12-12 19:07

What is std::pair for, why would I use it, and what benefits does boost::compressed_pair bring?

相关标签:
10条回答
  • 2020-12-12 20:06

    It's standard class for storing a pair of values. It's returned/used by some standard functions, like std::map::insert.

    boost::compressed_pair claims to be more efficient: see here

    0 讨论(0)
  • 2020-12-12 20:06

    std::pair comes in handy for a couple of the other container classes in the STL.

    For example:

    std::map<>
    std::multimap<> 
    

    Both store std::pairs of keys and values.

    When using the map and multimap, you often access the elements using a pointer to a pair.

    0 讨论(0)
  • 2020-12-12 20:07

    Additional info: boost::compressed_pair is useful when one of the pair's types is an empty struct. This is often used in template metaprogramming when the pair's types are programmatically inferred from other types. At then end, you usually have some form of "empty struct".

    I would prefer std::pair for any "normal" use, unless you are into heavy template metaprogramming.

    0 讨论(0)
  • 2020-12-12 20:08

    What is std::pair for, why would I use it?

    It is just as simple two elements tuple. It was defined in first version of STL in times when compilers were not widely supporting templates and metaprogramming techniques which would be required to implement more sophisticated type of tuple like Boost.Tuple.

    It is useful in many situations. std::pair is used in standard associative containers. It can be used as a simple form of range std::pair<iterator, iterator> - so one may define algorithms accepting single object representing range instead of two iterators separately. (It is a useful alternative in many situations.)

    0 讨论(0)
提交回复
热议问题