1. 程式人生 > >c++ 返回指定元素連續相等的位置索引(equal_range)

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()) << '
\n'; // 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()) << '\n'; // 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()) << '\n'; return 0; }