15,993,109 members
See more:
I have a Vector of structure that is sorted on based of a variable.

For ex:
struct Client {
string name;
int sm_index;
int client_id;
int user_id;
}

Sorted on based of sm_index.

How can i find and fetch the data of that struture whose sm_index matches our target structure.

We have below vector and no. structures added in to it.

vector <client> CLIENT;

What I have tried:

Have studied about find() fuction but unable to understand how to use it.
Posted
Updated 26-Mar-18 23:48pm

## Solution 1

Maciej Los 27-Mar-18 5:51am
5ed!
Richard MacCutchan 27-Mar-18 6:18am
Thank you, you are too generous.
Maciej Los 27-Mar-18 6:47am
Who, me? Never! :laugh:

## Solution 2

Thats sounds poor, because iteration is one main standout feature of the vector container class.

If your vector is sorted I would suggest the faster binary search but I think that you may consider this in a later stage of your project.

Maciej Los 27-Mar-18 5:51am
5ed!
Vishal Bhatia0112 27-Mar-18 6:00am
binary_search returns boolean value as per it's search but we need an iterator for same that is returned by find() or find_if() but again they use linear approach(poor).

I am thinking to write my own binary_search function that will return iterator to the found structure.

Any other suggestions are welcome.

## Solution 3

Here's an example of how to use binary_search :

bool Compare( const Client& lhs, const Client& rhs )
{
return ( lhs.client_id < rhs.client_id );
}

bool DoesClientExist( const Client &client, std::vector <Client> clientVec )
{
return binary_search( clientVec.begin(), clientVec.end(), client, Compare );
}

Vishal Bhatia0112 27-Mar-18 5:48am
binary_search returns boolean value as per it's search but we need an iterator for same that is returned by find() or find_if() but again they use linear approach(poor).

I am thinking to write my own binary_search function that will return iterator to the found structure.

Any other suggestions are welcome.
Rick York 27-Mar-18 12:50pm
I don't know of a binary_search variation that returns an iterator but I would be very surprised if someone has not make one already. Regardless, the code is in algorithm and it appears that it would be fairly easy to adjust it return the iterator instead of a boolean value.
Rick York 27-Mar-18 12:54pm
With a little searching, I found this little article : http://wordaligned.org/articles/binary-search. There are some very good tips in it.