Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and When should I use std::pair

Tags:

c++

std-pair

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?

like image 351
yolowex Avatar asked Oct 17 '25 02:10

yolowex


1 Answers

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.

like image 194
Goswin von Brederlow Avatar answered Oct 18 '25 14:10

Goswin von Brederlow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!