vector 的 emplace_back 与 push_back

emplace_back 可以直接转发参数到 President 的构造函数 , 避免用 push_back 时的额外复制或移动操作。

示例如下:

 1 #include <vector>
 2 #include <string>
 3 #include <iostream>
 4  
 5 struct President
 6 {
 7     std::string name;
 8     std::string country;
 9     int year;
10  
11     President(std::string p_name, std::string p_country, int p_year)
12         : name(std::move(p_name)), country(std::move(p_country)), year(p_year)
13     {
14         std::cout << "I am being constructed.\n";
15     }
16     President(President&& other)
17         : name(std::move(other.name)), country(std::move(other.country)), year(other.year)
18     {
19         std::cout << "I am being moved.\n";
20     }
21     President& operator=(const President& other) = default;
22 };
23  
24 int main()
25 {
26     std::vector<President> elections;
27     std::cout << "emplace_back:\n";
28     elections.emplace_back("Nelson Mandela", "South Africa", 1994);
29  
30     std::vector<President> reElections;
31     std::cout << "\npush_back:\n";
32     reElections.push_back(President("Franklin Delano Roosevelt", "the USA", 1936));
33  
34     std::cout << "\nContents:\n";
35     for (President const& president: elections) {
36         std::cout << president.name << " was elected president of "
37                   << president.country << " in " << president.year << ".\n";
38     }
39     for (President const& president: reElections) {
40         std::cout << president.name << " was re-elected president of "
41                   << president.country << " in " << president.year << ".\n";
42     }
43 }

输出:

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.

 

 

上一篇:Ruby类,模块1


下一篇:pandas统计功能