Advertisement
Guest User

Untitled

a guest
Mar 23rd, 2019
63
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. // démonstration emplace c++11 vs. c++17
  2. // rene-d 2019
  3.  
  4. //#include <bits/stdc++.h>
  5. #include <iostream>
  6. #include <vector>
  7. #include <unordered_map>
  8. using namespace std;
  9.  
  10. struct toto
  11. {
  12. int a;
  13.  
  14. explicit toto(int _a)
  15. {
  16. cout << "toto() int " << _a << endl;
  17. a = _a;
  18. }
  19.  
  20. toto()
  21. {
  22. cout << "toto()" << endl;
  23. a = 1;
  24. }
  25.  
  26. virtual ~toto()
  27. {
  28. cout << "~toto()" << endl;
  29. }
  30. };
  31.  
  32. void test_vector()
  33. {
  34. vector<toto> t;
  35.  
  36. #if _LIBCPP_STD_VER > 14 // C++17 et suivants (constante clang++)
  37. auto &&r1 = t.emplace_back(); // auto& fonctionne aussi
  38. r1.a = 100;
  39. #else
  40. auto &&r2 = t.emplace(t.end());
  41. r2->a = 1000;
  42. #endif
  43.  
  44. for (auto &&it : t)
  45. cout << "vector " << it.a << endl;
  46. }
  47.  
  48. void test_map()
  49. {
  50. unordered_map<int, toto> m;
  51.  
  52. auto &&r2 = m.emplace(std::piecewise_construct,
  53. std::forward_as_tuple(20),
  54. std::forward_as_tuple());
  55. r2.first->second.a = 200;
  56.  
  57. #if _LIBCPP_STD_VER > 14
  58. // c++17 autorise une syntaxe plus simple
  59. auto &&r3 = m.try_emplace(30);
  60. r3.first->second.a = 300;
  61. #endif
  62.  
  63. for (auto &&it : m)
  64. cout << "map " << it.first << " " << it.second.a << endl;
  65. }
  66.  
  67. int main()
  68. {
  69. test_vector();
  70. cout << "---------------------------------" << endl;
  71. test_map();
  72. }
  73.  
  74. /* sortie C++11
  75. toto()
  76. vector 1000
  77. ~toto()
  78. ---------------------------------
  79. toto()
  80. map 20 200
  81. ~toto()
  82. */
  83.  
  84. /* sortie C++17
  85. toto()
  86. vector 100
  87. ~toto()
  88. ---------------------------------
  89. toto()
  90. toto()
  91. map 30 300
  92. map 20 200
  93. ~toto()
  94. ~toto()
  95. */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement