Java等效于C ++ equal_range(或lower_bound& upper_bound) [英] Java equivalent of c++ equal_range (or lower_bound & upper_bound)
问题描述
我有一个排序的对象列表,我想找到一个对象的第一个匹配项和最后一个匹配项.在C ++中,我可以轻松使用std :: equal_range(或仅使用一个lower_bound和一个upper_bound).
I have a List of object sorted and I want to find the first occurrence and the last occurrence of an object. In C++, I can easily use std::equal_range (or just one lower_bound and one upper_bound).
例如:
bool mygreater (int i,int j) { return (i>j); }
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;
// using default comparison:
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
bounds=std::equal_range (v.begin(), v.end(), 20); // ^ ^
// using "mygreater" as comp:
std::sort (v.begin(), v.end(), mygreater); // 30 30 20 20 20 10 10 10
bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); // ^ ^
std::cout << "bounds at positions " << (bounds.first - v.begin());
std::cout << " and " << (bounds.second - v.begin()) << '\n';
return 0;
}
在Java中,似乎没有简单的对等关系吗?
In Java, there seems to be no simple equivalence? How should I do with the equal range with
List<MyClass> myList;
顺便说一句,我使用的是标准导入java.util.List;
By the way, I am using a standard import java.util.List;
推荐答案
In Java, you use Collections.binarySearch
to find the lower bound of the equal range in a sorted list (Arrays.binarySearch
provides a similar capability for arrays). Then you continue iterating linearly until you hit to the end of the equal range.
这些方法适用于实现 Comparable
的方法界面.对于未实现Comparable
的类,可以提供 custom 的实例
These methods work for methods implementing the Comparable
interface. For classes that do not implement the Comparable
, you can supply an instance of a custom Comparator
for comparing the elements of your specific type.
这篇关于Java等效于C ++ equal_range(或lower_bound& upper_bound)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!