Advertisement
RobertDeMilo

RB4.9 Класс string view

Apr 25th, 2024
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <string_view>
  4. #include <string>
  5. #include <vector>
  6.  
  7. using namespace std;
  8.  
  9. vector<string> SplitIntoWords(const string& str)
  10. {
  11.     vector<string> result;
  12.     auto str_begin = begin(str);
  13.     const auto str_end = end(str);
  14.  
  15.     while(true)
  16.     {
  17.         auto it = find(str_begin,str_end,' ');
  18.         result.push_back(string(str_begin,it));
  19.  
  20.         if(it==str_end)
  21.         {
  22.             break;
  23.         }
  24.         else
  25.         {
  26.             str_begin = it+1;
  27.         }
  28.     }
  29.  
  30.     return result;
  31. }
  32.  
  33. vector<string_view> SplitIntoWordsView(const string& s)
  34. {
  35.  
  36.     string_view str = s;
  37.     vector<string_view> result;
  38.  
  39.     //string_view работает с позициями в строках, а не с итераторами
  40.  
  41.     size_t pos =0;
  42.     const size_t pos_end = str.npos;
  43.  
  44.     while(true)
  45.     {
  46.         size_t space = str.find(' ', pos);
  47.         result.push_back(
  48.                 space == pos_end
  49.                 ?str.substr(pos)
  50.                         :str.substr(pos,space-pos));
  51.  
  52.         if(space == pos_end)
  53.         {
  54.             break;
  55.         }
  56.         else
  57.         {
  58.             pos = space + 1;
  59.         }
  60.     }
  61.  
  62.     return result;
  63. }
  64.  
  65. string GenerateText()
  66. {
  67.     const int SIZE = 10'000'000;
  68.     string text(SIZE,'a');
  69.  
  70.  
  71.     for(int i=100;i<SIZE;i+=100)
  72.     {
  73.         text[i]= ' ';
  74.     }
  75.  
  76.     return text;
  77. }
  78.  
  79. int main()
  80. {
  81.     const string text = GenerateText();
  82.  
  83.     {
  84.         //LOG_DURATION("string");
  85.         const auto words = SplitIntoWords(text);
  86.         cout<<words[0]<<"\n";
  87.  
  88.     }
  89.  
  90.     {
  91.         //LOG_DURATION("string_view");
  92.         const auto words = SplitIntoWordsView(text);
  93.         cout<<words[0]<<"\n";
  94.  
  95.     }
  96. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement