C++11 vector之vector::emplace与emplace_back
程序员文章站
2022-03-01 22:17:45
...
emplace_back可代替push_back,比push_back减少一次move操作,这里就放一些代码用例和参考博客
// reference: https://en.cppreference.com/w/cpp/container/vector/emplace_back
#include <vector>
#include <string>
#include <iostream>
struct President
{
std::string name;
std::string country;
int year;
President(std::string p_name, std::string p_country, int p_year)
: name(std::move(p_name)), country(std::move(p_country)), year(p_year)
{
std::cout << "I am being constructed.\n";
}
President(President&& other)
: name(std::move(other.name)), country(std::move(other.country)), year(other.year)
{
std::cout << "I am being moved.\n";
}
President& operator=(const President& other) = default;
};
int main()
{
std::vector<President> elections;
std::cout << "emplace_back:\n";
elections.emplace_back("Nelson Mandela", "South Africa", 1994);
std::vector<President> reElections;
std::cout << "\npush_back:\n";
reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
std::cout << "\nContents:\n";
for (President const& president: elections) {
std::cout << president.name << " was elected president of "
<< president.country << " in " << president.year << ".\n";
}
for (President const& president: reElections) {
std::cout << president.name << " was re-elected president of "
<< president.country << " in " << president.year << ".\n";
}
}
/*
Output:
emplace_back:
I am being constructed.
push_back:
I am being constructed.
I am being moved.
Contents:
Nelson Mandela was elected president of South Africa in 1994.
Franklin Delano Roosevelt was re-elected president of the USA in 1936.
*/
参考博客:
[1]:C++11 vector使用emplace_back代替push_back,这里还有insert、push_front对应的操作。
[2]:vector的 emplace 和 insert 以及使用vector进行iterator遍历 且 erase的时候注意事项
[3]:C++11中vector的emplace_back用法及输入输出操作符的重载
推荐阅读
-
C++11 vector之vector::data
-
C++ std::vector 的 emplace_back 能否完全取代 push_back
-
C++11 之 emplace_back() 与 push_back() 的区别
-
c++11 之emplace_back 与 push_back的区别
-
c++11新特性(7)之push_back与emplace_back之间的区别
-
emplace_back和push_back区别,以及vector内存变化
-
vector中push_back和emplace_back的区别
-
C++ STL 容器vector添加元素函数emplace_back()和push_back()的使用差异
-
C++11: vector::push_back和vector::emplace_back的区别
-
c++ vector容器emplace_back() 和 push_back 的区别