首頁  >  問答  >  主體

C++,在sort中使用谓词会怎样排序?

用来学习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;    
}
伊谢尔伦伊谢尔伦2714 天前554

全部回覆(1)我來回復

  • ringa_lee

    ringa_lee2017-04-17 14:45:44

    排序的結果是正確的
    不過只有排序之後,unqiue的結果才符合你的要求(大概,你沒講你什麼要求)~~
    文檔中的unique示例實現確實只能針對有序的區間去重。 。
    所以不奇怪使用.size()會導致那種結果
    樓主的問題到底是什麼。 。

    回覆
    0
  • 取消回覆