O
O
oftywave2020-12-08 18:00:51
C++ / C#
oftywave, 2020-12-08 18:00:51

Vector - element declaration, what's the difference between the two ways?

what's the difference between

std::vector<std::string> vec_m = { "vec1", "vec2", "vec3" };


std::vector<std::string> vec_m;
vec_m.push_back("vec1");
vec_m.push_back("vec2");
vec_m.push_back("vec3");


std::vector<std::string> vec_m;
vec_m.emplace_back("vec1");
vec_m.emplace_back("vec2");
vec_m.emplace_back("vec3");


the result is the same, it is interesting to know what is the difference

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mercury13, 2020-12-08
@oftywave

First way: initializer_list is created, constructor is called. Most effective for simple blunt objects.
The second way is equivalent to push_back(string("vec1")) and relies heavily on parameter optimization. Least efficient.
The third way is guaranteed not to create intermediate objects (calls the string(const char*) constructor already in place). Together with reserve(3), it is most efficient for managed objects.
UPD. 2 and 3 for string() are not very different due to efficient wrapping. But for larger objects 3 is better.
UPD2. Starting with C++20, 1 is better, but only because C++ has learned to make full-fledged strings when compiling - that is, the managed string object has acquired some dumb traits.
UPD3. No compiler supports constexpr string yet. But no one has a stable 20 yet, right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question