How can I find an element in a vector if I don't care about case. For example, if I have in cmp name = "tOM" addr = "LONDON" and I want it to find an element with values name = "Tom" addr = "London" that I have saved in vector? I enclose the whole program https://onecompiler.com/cpp/3xy2j7dmd .
bool Company::cmpNA2 (const Company &a, const Company &b)
{
if ( (strcasecmp(a.getName().c_str(), b.getName().c_str()) != 0) )
return ( strcasecmp(a.getName().c_str(), b.getName().c_str()) );
return ( strcasecmp(a.getAddr().c_str(), b.getAddr().c_str()));
}
bool CVATRegister::invoice ( const string &name, const string &addr, unsigned int amount )
{
Company cmp(name, addr,"-1");
sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
{
if ( (strcasecmp(a.getName().c_str(), b.getName().c_str()) != 0) )
return ( strcasecmp(a.getName().c_str(), b.getName().c_str()) );
return ( strcasecmp(a.getAddr().c_str(), b.getAddr().c_str()));
});
auto itr = lower_bound(DCompany.begin(), DCompany.end(), cmp, &Company::cmpNA2);
// cout << itr->getTotalIncome() << itr->getId() << endl; <--- Nothing
CodePudding user response:
The first thing is that std::sort
requires you to return true
or false
. The issue is that strcasecmp
returns an int
denoting whether the first item comes before, is equal, or after the second item (-1, 0, 1). That's three values, not just true
or false
.
To simplify your code, you could do something similar to this:
bool CVATRegister::invoice ( const string &name, const string &addr, unsigned int amount )
{
std::sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
{
return strcasecmp(a.getName().c_str(), b.getName().c_str()) < 0;
});
}
Since strcasecmp
returns -1 if the first item is placed before the second item, then the predicate simply returns true
if the result is < 0
, and false
otherwise.