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;
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With