Difference between make_pair and curly brackets {

2020-03-07 06:42发布

问题:

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;

回答1:

I tried this in an online compiler, and as far as I can see the optimized assembly for make_pair is identical to {} syntax.

https://godbolt.org/z/P7Ugkt



回答2:

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.



回答3:

{x, y} in v.push_back({x, y}) is aggregate initialization (since C++11) of v's value_type, whereas std::make_pair is a function creating and std::pair with types deduced from its arguments.

One advantage of push_back({x, y}) over emplace_back(x, y) is that you could keep small structures simple (without constructors) like this:

#include <vector>

struct A {
    int x;
    int y;
    // A(int _x, int _y) : x{_x}, y{_y} {}
};

int f()
{
    std::vector<A> v;
    v.push_back({1, 2});
    // v.emplace_back(1, 2); // doesn't compile unless constructor is uncommented
}

Example.



标签: c++ std-pair