2013-10-20 56 views
3

我有一個std::vector,我知道它是排序的。使用std::binary_search我可以在日誌時間內找到元素是否在向量中。不幸的是,std::binary_search在成功的情況下不會返回向量中元素的索引(或者如果它不確定如何訪問它)。 std::find會給我一個元素的迭代器,但它並不使用矢量排序的事實,因此它在線性時間內運行而不記錄時間。我知道我可以簡單地實現我自己的二分查找算法,但我想知道是否有方法在標準中執行此操作。C++ - 排序std :: vector中的元素索引

+2

[性病:: LOWER_BOUND](http://en.cppreference.com/w/cpp/algorithm/lower_bound)? –

回答

5

你想使用lower_bound()函數。使它通常有用,但有時候會達到你想要的目的。

+0

我會看看是否有用,謝謝。 –

+0

請參閱[http://www.cplusplus.com/reference/algorithm/binary_search/](http://www.cplusplus.com/reference/algorithm/binary_search/),瞭解如何使用binary_search'的示例'LOWER_BOUND()'。 – TAS

4

可以使用std::lower_bound(O(日誌(N))和std::distance(O(1)用於隨機接入的迭代器):

auto lower = std::lower_bound(v.begin(), v.end(), val); 
// check that value has been found 
const bool found = lower != v.end() && *lower == val; 

然後,無論是

auto idx = std::distance(v.begin(), lower); 

或純算術:

auto idx = lower - v.begin(); 
+2

您需要檢查'* lower'是否是'val'。你還需要檢查'lower!= end'。 – Nawaz

+0

@Nawaz正確,補充說,因爲它很容易錯過。 – juanchopanza

0

扭捏std::binary_search你可以得到:

template<typename Iter, typename T> 
Iter my_find(Iter begin, Iter end, T value) 
{ 

    Iter i = std::lower_bound(begin, end, value); 

    if (i != end && *i == value) 
     return i; // found in container 
    else 
     return end; // not found 
} 

auto it = my_find(v.begin(), v.end(), val); //it is your iterator 
相關問題