Many C ++ books encourage us to replace arrays with vectors and replace traditional strings with strings. I always believe that this can be done. After doing so, it will reduce the workload and improve efficiency. Knowing that is the same thing. Actually, it is the same thing. Every time you use string, there will always be such a problem. I was thinking that the reason why accelerated C ++ is so famous may be that the author directly taught us how to think in C ++. This book only reads a small part, but there is an example to illustrate the problem-the author teaches us how to think in C ++.
The following two programs implement the same function and read a row. For example, they split the words in the sentence.
Procedure 1:
#include<iostream>#include<vector>#include<cctype>#include<string>using namespace std;vector<string>split(const string&s){vector<string> ret;typedef string::size_type string_size;string_size i = 0;while( i != s.size() ){while( i != s.size() && isspace(s[i]))++i;string_size j =i;while( j != s.size() && ! isspace( s[j]))++j;if( i != j){ret.push_back( s.substr(i,j - 1 ));i = j;}}return ret;}int main(){string str;getline( cin, str);vector<string> vec = split( str );cout << " vec.size() = " << vec.size() << endl;cout << str << endl;return 0;}
Program 2 (pure C ++ implementation ):
#include<iostream>#include<vector>#include<cctype>#include<string>#include<algorithm>using namespace std;bool space( char c){return isspace(c);}bool not_space( char c){return !isspace(c);}vector<string> split( const string& str){typedef string::const_iterator iter;vector<string> ret;iter i = str.begin();while( i != str.end()){i = find_if( i , str.end(), not_space);iter j = find_if( i, str.end(), space);if ( i != str.end() )ret.push_back( string( i,j ));i = j;}return ret;}int main(){string str;getline( cin, str);vector<string> vec = split( str );cout << "vec.size() = " << vec.size() << endl; cout << str << endl;return 0; }
There is also a good example in the book, which can be used to check whether a character string is familiar with STL and use a line of code to determine whether a character string is a reply:
# Include <iostream> # include <algorithm> # include <string> using namespace STD; int main () {string STR; CIN> STR; // The core code is like this line if (equal (Str. begin (), str. end (), str. rbegin () {cout <STR <"is a plaindrome" <Endl ;} else {cout <STR <"is not a plaindrome" <Endl;} return 0 ;}