我有一个向量pairs
。假设它是这样的:STL排序向量找到第一个元素小于或等于给定值
vector<pair<int,int>> vec = { {1,12}, {1,5}, {1,6}, {1,9}, {3,9}, {3,11}, {3,13}, {3,4}, {5,9}, {5,91}, {13,8}, {16,8}, {20,8}, {20,81} };
pairs
按第一个元素排序。
给定一个pair
,我需要找到向量的最后一个pair
的索引,该向量的第一个元素小于或等于给定对的第一个元素。如果去年pair
,另一对骗其左边的第一个元素的值相同,我首先需要的所有那些对:
<4,10> => 4 (vec[4] is <3,9>, the elements with the largest first value less than or equal to 4 are those with first element as 3, and there are 4 pairs with a 3 in the first element, at indices 4-7, so return the first of those pairs)
<0,10> => -1, since no element exists to its right.
<1,6> => 0 (vec[0] is <1,12>. There is no pair whose first element is less than 1, and there are 4 pairs, including <1,6> whose first element is 1. So we need the first of these 4 pairs.)
<23,81> => 12 (vec[12] is <20,8>)
条件:我只需要使用标准的算法,如upper_bound
,binary_search
和lower_bound
。我想这一点,但它没有严重:
vector<pair<int,int>> vec = { {1,12}, {1,5}, {1,6},{1,9}, {3,9}, {3,11}, {3,13}, {3,4}, {5,9}, {5,91}, {13,8}, {16,8}, {20,8}, {20,81} };
auto i = std::lower_bound(vec.begin(), vec.end(), make_pair<int,int>(4,10),
[](const pair<int,int>& f1, const pair<int,int>& f2) { return f1.first < f2.first; });
cout << i-vec.begin();
'(4 - 1,10)'?那是什么? – SexyBeast
@SexyBeast我更新了答案,希望现在一切都清楚! – gsamaras
这是一个了不起的答案!谢谢哥们!我会在一段时间内给它一个奖励!当你在这里时,矢量初始化代码已经被美元符号剪掉了! – SexyBeast