c++ - Finding the upper bound of vector of pairs based on second value of pair -
i have vector of pair "v" sorted according second value of pair. want find out upper bound of vector "v" according second value of pair -- while finding upper bound want ignore first vector (std::vector<int>
) of pair of vectors.
int main () { std::vector<std::pair<std::vector<int>, int> > v; //10 10 10 20 20 20 30 30 std::vector<int> a; a.push_back(1); v.push_back(make_pair(a,10)); a.push_back(2); v.push_back(make_pair(a,10)); a.push_back(3); v.push_back(make_pair(a,10)); a.push_back(4); v.push_back(make_pair(a,20)); a.push_back(5); v.push_back(make_pair(a,20)); a.push_back(6); v.push_back(make_pair(a,20)); a.push_back(7); v.push_back(make_pair(a,30)); a.push_back(8); v.push_back(make_pair(a,30)); std::vector<std::pair<std::vector<int>, int> >::iterator low,up; std::vector<int> b; up= std::upper_bound (v.begin(), v.end(), make_pair(b,25)); std::cout << "upper_bound @ position " << (up - v.begin())<<" val="<<v[(up-v.begin())].second<< '\n'; return 0; }
i want upper_bound position returned 6 , value returned 30. using above code incorrectly getting position 0 , value 10. can please suggest how can upper bound based on second value of pair , ignore first value of pair
you need offer compare
function upper_bound
template<typename t> bool compare(const t &a,const t &b){ return a.second<b.second; }
and change:
up= std::upper_bound (v.begin(), v.end(), make_pair(b,25));
to:
up= std::upper_bound (v.begin(), v.end(), make_pair(b,25),compare<pair<vector<int>,int>>);
Comments
Post a Comment