Arun
Arun

Reputation: 2373

c++ find vector of element present in the string

I have vector of strings. It contains some names. I need to search whether particular string is present in the vector. Eg: vector of string contains "Name" and "Age". Search string is "NameXYZ". So I have to search whether "NameXYZ" contains any of the vector element. Since one of the vector element is "Name", it should return true. Is there any possibility to achieve this without iterating.

Upvotes: 0

Views: 114

Answers (2)

Tiger4Hire
Tiger4Hire

Reputation: 1091

The more complex is answer is SOMETIMES

What you are looking for is something like a hash set. Or for your situation hash map with Key=Name and Value=Age.
This works by defining a function that turns a string into a number, called a hash. When you want to test whether the string is in the list, you calculate what number it has. You then get a list of potential candidates and iterate through those. If you are lucky, every string has a unique number and you need to test at most one string. You still have to search for the number, but if you use the standard container, you can be certain that it is optimized. Unless you want to spend a long time making your own, it's a simple easy win. However, be aware that it is very hard to get any search faster than O(Log(N)) complexity. This method is still O(log(N)) complex under the hood, as it has to still search for the hash.

Upvotes: 0

Zig Razor
Zig Razor

Reputation: 3495

The answer is NO.

It's impossibile to search something in a vector without iterating.

The vector is unorder and unmapped container so you need to iterating to it to find something.

I attach you this link to the cppreference site:

std::vector - cppreference.com

Upvotes: 2

Related Questions