Find() function of the set library does not return whether or not it found

Asked

Viewed 76 times

4

I’m writing a little program for a college exercise and I’m having second thoughts about find(). I must enter two integer numbers, check if the first number exists within the set previously defined. If it exists, I must insert the second integer in the set.

So I did:

cin >> valor >> valord;
if (di.find(valor))
   di.insert(valor);

Where di is mine set defined with values already filled.

You’re making the following mistake:

[Error] could not Convert 'di.Std::set<_Key, _Compare, _Alloc>::find, Std::allocator >(((const key_type)(& value))'from 'Std::set::iterator {aka Std::_Rb_tree_const_iterator}' to 'bool'

Could someone explain to me if the function find returns true or false?

2 answers

4


This function does not return a boolean, according to documentation returns an iterator with the position found, or the position after the end if nothing is found. So you should do something like this:

if (di.find(valor) != di.end()) di.insert(valord);

I put in the Github for future reference.

  • Thank you very much !!

  • 2

    @mahatt see on [tour] the best way to say thank you.

4

There are 2 errors in the code.

// errado
cin >> valor >> valord;
if (di.find(valor)) // erro de sintaxe: find retorna um "iterator" e não um bool
  di.insert(valor); // erro lógico: deve ser "valord"

// certo
cin >> valor >> valord;
if (di.find(valor) != di.end()) // <----
  di.insert(valord);            // <----

Browser other questions tagged

You are not signed in. Login or sign up in order to post.