Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between make_pair and curly brackets { } for assigning a pair in C++?

Tags:

c++

std-pair

I didn't find anyone answering this, is there any difference between the following :

v.push_back({x, y});

and :

v.push_back(make_pair(x, y));

Assuming that v was declared this way :

vector<pair<int,int> > v;
like image 968
Noueman Khalikine Avatar asked Sep 08 '18 14:09

Noueman Khalikine


People also ask

What is the difference between curly brackets and square brackets?

The curly brackets are used to denote a block of code in a function. So, say we need a function to calculate the standard error we might do this. The square brackets are used to subset vectors and data frames.

What is the use of curly brackets in C programming?

In programming, curly braces (the { and } characters) are used in a variety of ways. In C/C++, they are used to signify the start and end of a series of statements. In the following expression, everything between the { and } are executed if the variable mouseDOWNinText is true. See event loop.

What is the use of Make_pair?

The make_pair() function, which comes under the Standard Template Library of C++, is mainly used to construct a pair object with two elements. In other words, it is a function that creates a value pair without writing the types explicitly.

What are curly brackets called in C?

Curly braces (also referred to as just "braces" or as "curly brackets") are a major part of the C++ programming language. They are used in several different constructs, outlined below, and this can sometimes be confusing for beginners.


1 Answers

I think you might have accepted that answer a little too quickly. The commonly accepted way to do this is like this:

vec.emplace_back (x, y);

And if you look at Godbolt, you can see that this inlines everything (which may or may not be what you want):

https://godbolt.org/z/aCl02d

Run it at Wandbox:

https://wandbox.org/permlink/uo3OqlS2X4s5YpB6

Code:

#include <vector>
#include <iostream>

int x = 1;
int y = 2;
std::vector<std::pair<int,int>> vec;

int main () {
    vec.push_back(std::make_pair(x, y));
    std::cout << "make_pair done\n";
    vec.push_back({x, y});
    std::cout << "push_back done\n";
    vec.emplace_back (x, y);
    std::cout << "emplace_back done\n";

    for (std::pair <int, int> p : vec)
    {
        std::cout << p.first << ", " << p.second << "\n";
    }
}

Output:

make_pair done
push_back done
emplace_back done
1, 2
1, 2
1, 2

Of course, everything runs faster if you reserve the appropriate number of elements in the vector up front. Maybe that's what the people posing this question are really wanting you to say.

like image 129
Paul Sanders Avatar answered Oct 27 '22 14:10

Paul Sanders