本程序演示:怎样将一个string字符串输入到一个vector
// sort and unique #include <iostream> #include <string> #include <vector> #include <algorithm> using std::cin; using std::cout; using std::ends; using std::endl; using std::string; using std::vector; using std::sort; void show(vector<string> const &words); void elimDups(vector<string> &words); int main(void) { string str("the quick red fox jumps over the slow red turtle"); //string str(""); string separators = " \t:;,\v\n\r\f"; string word; vector<string> vec; std::string::size_type startPos = 0, endPos = 0; std::string::size_type /*count = 0,*/ wordLen = 0; while ((startPos = str.find_first_not_of(separators, endPos)) != std::string::npos) { // ++count; endPos = str.find_first_of(separators, startPos); if (endPos == std::string::npos) { wordLen = str.size() - startPos; } else { wordLen = endPos -startPos; } word.assign(str.begin() + startPos, str.begin() + startPos + wordLen); vec.push_back(word); } // show vec info show(vec); elimDups(vec); return 0; } void elimDups(vector<string> &words) { sort(words.begin(), words.end()); show(words); auto end_unique = unique(words.begin(), words.end()); show(words); words.erase(end_unique, words.end()); show(words); } void show(vector<string> const &words) { for (auto s : words) cout << s << " "; cout << endl; return; }
程序输出:
[lhf@localhost study]$ ./23 the quick red fox jumps over the slow red turtle fox jumps over quick red red slow the the turtle fox jumps over quick red slow the turtle the red fox jumps over quick red slow the turtle