fork download
  1. #include <iostream>
  2. #include <list>
  3. #include <numeric>
  4. #include <chrono>
  5. #include <string>
  6. #include <memory>
  7.  
  8. using namespace std;
  9.  
  10. template< typename T, template<typename, typename> class Container>
  11. class ContainerTemplate: public Container<T, allocator<T>>
  12. {
  13. public:
  14. size_t inlet_whole_length()
  15. {
  16. size_t result(0);
  17. for(auto it: *this)
  18. {
  19. result+=it.size();
  20. }
  21. return result;
  22. }
  23.  
  24.  
  25. T whole_inlet_containers2container()
  26. {
  27. T result;
  28. result.reserve(inlet_whole_length());
  29. for(auto a:*this)result.insert(result.end(), a.begin(), a.end());
  30. return result;
  31. }
  32.  
  33. };
  34.  
  35. template< typename T, template<typename, typename> class Container>
  36. class ContainerTemplate2: public Container<T, allocator<T>>
  37. {
  38. public:
  39. size_t inlet_whole_length()
  40. {
  41. size_t result(0);
  42. for(const auto &it: *this) //ссылка важна здесь
  43. {
  44. result+=it.size();
  45. }
  46. return result;
  47. }
  48.  
  49.  
  50. T whole_inlet_containers2container()
  51. {
  52. T result;
  53. result.reserve(inlet_whole_length());
  54. for(const auto &a:*this)result.insert(result.end(), a.begin(), a.end());
  55. return result;
  56. }
  57.  
  58. };
  59.  
  60. int main()
  61. {
  62.  
  63. const std::size_t Size = 75000;
  64. ContainerTemplate<string, list> vs;
  65. ContainerTemplate2<string, list> vs2;
  66.  
  67. for (std::size_t i = 0; i < Size; i++)
  68. {
  69. auto str = std::string(i,'s');
  70. vs.push_back(str);
  71. vs2.push_back(str);
  72. }
  73. auto start = std::chrono::high_resolution_clock::now();
  74. auto str = vs.whole_inlet_containers2container();
  75. auto end = std::chrono::high_resolution_clock::now();
  76.  
  77. std::chrono::duration<double> diff = end-start;
  78. std::cout << "Time without ref "<< diff.count() << " s\n";
  79.  
  80. start = std::chrono::high_resolution_clock::now();
  81. auto str2 = vs2.whole_inlet_containers2container();
  82. end = std::chrono::high_resolution_clock::now();
  83. diff = end-start;
  84. std::cout << "Time with ref "<< diff.count() << " s\n";
  85. }
  86.  
Success #stdin #stdout 3.72s 320832KB
stdin
Standard input is empty
stdout
Time without ref 1.29938 s
Time with ref 0.806544 s