用来学习C++的书事《C++ Primer》,看到书上关于谓词的这部分的时候,自己动手敲了一下,为什么输出结果是这样的啊?书上说可以按照字符串的长度来排序,然后我就想看下按照字符串长度从长到短和从短到长两种方式来排一下会怎样,结果发现他们虽然是按照字符串的长度分好了,可是长度相同的字符串之间并没有进行排序吖。
先放用来输入的文件
adada adada adada ddhu huafw fhau igk jjjj bbb iii www ccc jjj ppp ooo ddd ccc aaa ddd iii www ccc bbb dd
然后是输出的结果
smaller elimdups:
dd jjj bbb ccc www iii ddd aaa ccc ddd ooo ppp ccc www iii bbb igk jjjj fhau ddhu adada huafw adada
bigger elimdups :
adada huafw adada ddhu fhau jjjj jjj bbb ccc www iii ddd aaa ccc ddd ooo ppp ccc www iii bbb igk dd
elimdups
aaa adada bbb ccc dd ddd ddhu fhau huafw igk iii jjj jjjj ooo ppp www
下面是代码,我还把smaller,bigger函数里的size去掉了尝试了下,发现这样产生的结果就是正常的,一个从大到小一个从小到大。可以为什么用字符串的长度来比较就会这样呢?
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool smaller (const string str1, const string str2){
return str1.size() < str2.size();
}
bool bigger (const string str1, const string str2){
return str1.size() > str2.size();
}
void smaller_pre_elimdups (vector<string> &word){
sort(word.begin(), word.end(), smaller);
auto unique_end = unique(word.begin(), word.end());
word.erase(unique_end, word.end());
}
void bigger_pre_elimdups (vector<string> &word){
sort(word.begin(), word.end(), bigger);
auto unique_end = unique(word.begin(), word.end());
word.erase(unique_end, word.end());
}
void elimdups (vector<string> &word){
sort(word.begin(), word.end());
auto unique_end = unique(word.begin(), word.end());
word.erase(unique_end, word.end());
}
int main(){
ifstream input("filein.txt");
ofstream output("out.txt", ostream::app);
string reader;
vector<string> s_str;
vector<string> b_str;
vector<string> str;
while (getline(input, reader)){
istringstream rectord(reader);
string temp;
while (rectord >> temp){
s_str.push_back(temp);
b_str.push_back(temp);
str.push_back(temp);
}
}
smaller_pre_elimdups(s_str);
bigger_pre_elimdups(b_str);
elimdups(str);
output << '\n' << "smaller elimdups:" << '\n';
for (auto smaller : s_str)
output << smaller << " ";
output << '\n' << "bigger elimdups :" << '\n';
for (auto bigger : b_str)
output << bigger << " ";
output << '\n' << "elimdups" << '\n';
for (auto e : str)
output << e << " ";
output << endl;
return 0;
}
ringa_lee2017-04-17 14:45:44
The sorting result is correct
But only after sorting, can the result of unqiue
meet your requirements (probably, you didn’t mention your requirements)~~
Example implementation of unique
in the document It is true that only ordered intervals can be deduplicated. .
So it’s not surprising that using .size()
will lead to that kind of result
What is the original poster’s problem? .