Find Member Function in Vector in C++Similar to an array in any other language, a vector in C++ is dynamic; hence its size is not constant. Why vectors? Because C++ arrays are static and cannot have their widths changed after being defined, this is not ideal when storing a data set whose size is unknown. Example: Output: 3 ......................................... Process executed in 1.22 seconds Press any key to continue. Explanation This piece of code returns the element's index if it is present in the vector; else, it returns -1.
The function call runs over n elements in the vector in order to locate the key we're looking for, hence the time complexity is linear O(n). Simple comparisons are performed by iteratively walking over the vector with a constant O(1) space complexity. Taking Help of std::find_if() with std::distance()Finding an element in a vector using this method is advised if the search needs to fulfil a certain logic, such as finding an element's index in the vector using prime number logic. When our predicate (compare struct) returns true for any element in the first to last range, std::find if() delivers an iterator to that element. The function will return end(last), point past last, if there is no such key. The number of hops from first to last is returned by std::distance(). In our situation, it gives us the hops from the beginning of the vector up to the iterator's key, k, which is the positional index of the element we're looking for. The key index will depend on the number of hops. Example: Output: 3 ......................................... Process executed in 1.33 seconds Press any key to continue. Explanation
Next TopicSmart Pointer
|