1

I know I can mix two types with std::pair but what is the difference of using std::pair instead of a class I created?.

What are the advantages of each of them, and why should I use std::pair?

struct MyObject{
    int a;
    std::string b;

    MyObject(int p_a,std::string p_b)
    a:p_a , b:p_b
    {
    };
};

std::pair<int,std::string> DefaultPair=std::make_pair(20,"Default Pair"); 
//Why should I use this

MyObject MyPair(10,"My Custom Pair");
//When I can use this?

yolowex
  • 31
  • 5
  • 3
    I understand you are a cool professional person but I'm trying to learn and that is why I ask. I asked it because I couldn't find the answer anywhere else.@UlrichEckhardt – yolowex Jun 13 '22 at 09:02
  • 4
    Please read [ask] and take the [tour], it might illustrate my opinion a bit. And you're welcome to learn, I don't want to prevent that. BTW: There is also a `std::tuple`, which you should look at, though I guess it is mentioned in the two other questions that this one duplicates. – Ulrich Eckhardt Jun 13 '22 at 09:07
  • 1
    Another duplicate: https://softwareengineering.stackexchange.com/questions/344827/what-difference-is-there-between-using-a-struct-and-a-stdpair – user17732522 Jun 13 '22 at 09:08
  • 3
    The `std::pair` is very generic, and will have operations that you might not want (e.g. ordering, equality, ...). On the other hand, it is very generic and will have operations that you might not want to implement yourself (e.g ordering, equality, ...). – molbdnilo Jun 13 '22 at 09:32
  • 1
    vote to reopen: The questions are 3 and 11 years old, respectively. Standard has changed (e.g. pair vs. tuple), and this question is broader than just the comparison with "struct wiht two members". – peterchen Jun 13 '22 at 10:32
  • For the same reason you should use any other standard library component: because it is standard (so everyone understands what it does and how to deal with it). – n. m. could be an AI Jun 13 '22 at 12:16

1 Answers1

1

You should use std::pair when the types are template parameter without any better name to give them meaning. Because defining template <typename U, typename V> MyObject { U u; V v; }; just duplicates std::pair. It's always better to define your own struct with meaningful names for the members if you can.

Evg
  • 25,259
  • 5
  • 41
  • 83
Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42