c++ - C++11 searching a vector of objects -


i have 2 vectors

std::vector<myobj> v; std::vector<myobj2> z; 

the objects in vectors both contain int has id. want see if when looking through v has matching id in z

so thought use `std::find_if , lambda.

for (int i=0; < _z.size(); i++) {      myobj2 _g = _z.at(i);       auto iter = std::find_if(v.begin(), v.end(), [this](myobj o)       {         if (o.getid() == _g.getid())         {             std::cout << "we have match" << std::endl;         }         else         {             std::cout << "we not have match" << std::endl;        }     }); } 

but getting error dont understand.

43: member function 'getid' not viable: 'this' argument has type 'const myobj2', function not marked const

i dont understand has marked const , why?

an needing in .hpp?:

myobj2& operator= (const myobj2&); myobj2& operator== (const myobj2&);  

from cppreference find_if:

unarypredicate must meet requirements of predicate.

wich liks concept of predicate:

the predicate concept describes function object takes single iterator argument dereferenced , used return value testable bool.
in other words, if algorithm takes predicate pred , iterator first, should able test iterator using predicate via construct if (pred(*first)) {...}.
function object pred shall not apply non-constant function through dereferenced iterator. function object may pointer function or object of type appropriate function call operator.

there 2 requirements stated in text:

  1. your predicate (i.e. lambda) has return convertible bool. output cout not sufficient.
  2. your predicate not allowed call nonconst functions on argument (i.e. myobj)

however, code shows lots of compile errors nothing relates error stated in question. because did not provide sscce:

  • you did not capture _g in lambda expression
  • you compile errors if predicate not return convertible bool (see requirements predicate above)
  • you mismatched z , _z

i not errors described, because in example code copy values vectors instead of taking const reference. copying fine of course, , can apply non-const functions copies. have compileable mini-example of code here: http://ideone.com/o8tped

however, not how should implemented:

  • you should take references instead of copies of vector elements (i almost sure in reality)
  • to avoid error reported, have declare both getid functions const. should regardless of usage in algorithm, because functions don't change object should so.

Comments

Popular posts from this blog

java - activate/deactivate sonar maven plugin by profile? -

python - TypeError: can only concatenate tuple (not "float") to tuple -

java - What is the difference between String. and String.this. ? -