c++ 返回指定元素连续相等的位置索引(equal_range)

#include <iostream>     // cout
#include <algorithm>    // equal_range, sort
#include <vector>       // vector
using namespace std;
bool mygreater (int i,int j) { return (i>j); }

int main () {
    int myints[] = {10,20,30,30,20,10,10,20};
    vector<int> v(myints,myints+8);                         // 10 20 30 30 20 10 10 20
    pair<vector<int>::iterator,vector<int>::iterator> bounds;
    
    bounds=equal_range (v.begin(), v.end(), 10);
    cout << "bounds at positions " << (bounds.first - v.begin());
    cout << " and " << (bounds.second - v.begin()) << '
';
    
    // using default comparison:
    sort (v.begin(), v.end());                              // 10 10 10 20 20 20 30 30
    bounds=equal_range (v.begin(), v.end(), 10);            //          ^        ^
    
    cout << "bounds at positions " << (bounds.first - v.begin());
    cout << " and " << (bounds.second - v.begin()) << '
';
    
    // using "mygreater" as comp:
    sort (v.begin(), v.end(), mygreater);                   // 30 30 20 20 20 10 10 10
    bounds=equal_range (v.begin(), v.end(), 20, mygreater); //       ^        ^
    
    cout << "bounds at positions " << (bounds.first - v.begin());
    cout << " and " << (bounds.second - v.begin()) << '
';
    
    return 0;
}

原文地址:https://www.cnblogs.com/sea-stream/p/9816780.html