我有一個std::vector
,我知道它是排序的。使用std::binary_search
我可以在日誌時間內找到元素是否在向量中。不幸的是,std::binary_search
在成功的情況下不會返回向量中元素的索引(或者如果它不確定如何訪問它)。 std::find
會給我一個元素的迭代器,但它並不使用矢量排序的事實,因此它在線性時間內運行而不記錄時間。我知道我可以簡單地實現我自己的二分查找算法,但我想知道是否有方法在標準中執行此操作。C++ - 排序std :: vector中的元素索引
回答
你想使用lower_bound()函數。使它通常有用,但有時候會達到你想要的目的。
我會看看是否有用,謝謝。 –
請參閱[http://www.cplusplus.com/reference/algorithm/binary_search/](http://www.cplusplus.com/reference/algorithm/binary_search/),瞭解如何使用binary_search'的示例'LOWER_BOUND()'。 – TAS
可以使用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();
您需要檢查'* lower'是否是'val'。你還需要檢查'lower!= end'。 – Nawaz
@Nawaz正確,補充說,因爲它很容易錯過。 – juanchopanza
扭捏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
使用equal_range
而不是lower_bound
。
您不能簡單地檢查由std::lower_bound
返回的迭代器是否與結束時不同,以知道該元素是否在集合中。如果該元素不存在,則std::lower_bound
返回應該出現的位置,而不是集合的結尾。
參見:https://www.fluentcpp.com/2017/01/16/how-to-stdfind-something-efficiently-with-the-stl/
- 1. 由內部的元素排序std :: vector?
- 2. std :: vector元素中的const引用
- 3. std :: vector中的單個元素[C++]
- 4. 如何從索引中刪除std :: vector <>中的元素?
- 5. C++使用std ::指針列表重新排列std :: vector元素
- 6. 排序索引元素
- 7. C++ - 如何將std :: priority_queue中的元素複製到std :: vector
- 8. 擦除std :: vector的元素是否保留了排序?
- 9. 如何將std :: vector的某些元素移動到向量中的新索引?
- 10. 字符串排序 - std :: set或std :: vector?
- 11. 可排序的GET元素索引
- 12. 獲取C++中的元素索引
- 13. 推回C++ std :: vector中的元素,他們失去了信息
- 14. 排序「的std :: vector」的含類
- 15. 當push_back新元素到std :: vector
- 16. sizeof()std :: vector(C++)
- 17. std :: vector和std :: deque中元素的連續存儲位置
- 18. 在std :: set中查找std :: vector的元素
- 19. 訪問std :: vector中的元素<std :: reference_wrapper <Type>>
- 20. C++友元類的std :: vector的
- 21. 使用X,Y,Z索引std :: vector
- 22. Atomically std :: vector :: push_back()並返回索引
- 23. 在C++中修改元素的排序相關部分std :: set
- 24. C++如何搜索vector中的struct元素是否相等?
- 25. 是否vector ::擦除向量中的重新排序元素?
- 26. C++ std :: vector <std :: shared_ptr>
- 27. c#元素排序
- 28. 如何到達2d std :: vector的第N個元素(`std :: vector <std :: vector <T>>`)?
- 29. 如何通過不同的std :: vector的值對std :: vector進行排序?
- 30. std ::在C++中排序?
[性病:: LOWER_BOUND](http://en.cppreference.com/w/cpp/algorithm/lower_bound)? –