c++ - Find index of value in Vector, nearest to the input -


is there efficient method of finding index of value in vector, closest reference value?

computationally, if vector not sorted, can't expect less o(n), may or may not meet expectation. if doesn't, should change data structure. if does, use std::min_element, way:

#include <vector> #include <algorithm> #include <iostream>  int main() {     int refelem = 42;     std::vector<int> v{1, 5, 36, 50};     auto = min_element(begin(v), end(v), [=] (int x, int y)     {         return abs(x - refelem) < abs(y - refelem);     });      std::cout << std::distance(begin(v), i); // prints 2 } 

if vector sorted, on other hand, can use std::lower_bound() , std::upper_bound(), have logarithmic complexity.

if think complexity issue because of performance, do measurements before deciding change data structure. since vectors store elements in contiguous region of memory, linear search resulting in high cache hit rate outperform computationally more efficient algorithm on data structure allocates element here , there in memory, resulting in frequent cache misses.


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -