fork download
  1. #include <string>
  2. #include <iostream>
  3. #include <iomanip>
  4. #include <chrono>
  5.  
  6.  
  7. using namespace std;
  8.  
  9.  
  10. int main(int argc, const char * argv[])
  11. {
  12.  
  13. string s;
  14. for(int i = 0; i < 100000; ++i) s += rand()%26+'A';
  15.  
  16. {
  17. auto start = chrono::high_resolution_clock::now();
  18. string d;
  19. d.reserve(s.length()*3/2);
  20. for(size_t i = 0; i < s.length(); ++i)
  21. {
  22. d += s[i++];
  23. if (i < s.length())
  24. {
  25. d += s[i];
  26. d += '-';
  27. }
  28. }
  29. auto stop = chrono::high_resolution_clock::now();
  30. cout << chrono::duration_cast<chrono::nanoseconds>(stop-start).count() << endl;
  31. }
  32.  
  33. {
  34. auto start = chrono::high_resolution_clock::now();
  35.  
  36. string str;
  37. str.resize(s.length() * 3/2);
  38. size_t size = 0;
  39.  
  40. for (size_t i = 0; i < s.length(); ++i) {
  41. str[size++] = s[i++];
  42. if (i < s.length()) {
  43. str[size++] = s[i];
  44. if (i != s.length() - 1)
  45. str[size++] = '-';
  46. }
  47. }
  48. // ;-)
  49. str.resize(size);
  50.  
  51. auto stop = chrono::high_resolution_clock::now();
  52. cout << chrono::duration_cast<chrono::nanoseconds>(stop-start).count() << endl;
  53. }
  54.  
  55.  
  56. }
  57.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
995914
770078