user1355603
user1355603

Reputation: 305

Issues in searching through the vector?

I have a vector of the form given below (in C++):

 vector<pair<int,int> > u;

Now when the first element of u.first becomes equal to 12 then I want to break from the loop. I am using the following code for this:

 while(1){
    if((find(u.begin().first, u.end().first, 12)!=u.end().first))
            {
                    break;
            } 
   }

However, it gives me the error that

     'unable to resolve identifier first'

Upvotes: 0

Views: 132

Answers (1)

James McNellis
James McNellis

Reputation: 355357

std::find iterates over a range and returns an iterator to the first element in the sequence that matches the provided value (12, in your case). The iterators are not the element in the container, they are pseudo-references to elements in the container.

You have to dereference an iterator to get the element. So, u.begin()->first would be the first value of the initial element of the container. u.begin().first is nonsensical.

In any case, to find a matching element using an operation other than ==, you need to use find_if with a custom predicate. For example, using a lambda expression:

auto const it(std::find_if(u.begin(), u.end(), [](std::pair<int, int> const& v)
{
    return v.first == 12;
}));

if (it != u.end())
    continue;

Upvotes: 1

Related Questions