yolowex
yolowex

Reputation: 51

Why and When should I use 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?

Upvotes: 3

Views: 4036

Answers (1)

Goswin von Brederlow
Goswin von Brederlow

Reputation: 12322

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.

Upvotes: 2

Related Questions