Home > OS >  C Using upper_bound instead of find ()
C Using upper_bound instead of find ()

Time:04-03

I need advice on how to modify the program so that I can search using the upper/lower_bound function. The program works correctly(ok asserts) for the find () function. I sort the company database after each insertion or deletion, so that's probably not the problem In the link I enclose the whole program for a better understanding. https://onecompiler.com/cpp/3xxyvx8vw

bool Company::operator == (Company cmpx)  const
{ 

    return ( ( (strcasecmp(addr.c_str(), cmpx.addr.c_str()) == 0) 
            && (strcasecmp(name.c_str(), cmpx.name.c_str()) == 0) )
            || (id == cmpx.id)
    );
    
}

bool Company::operator < (Company cmpx) const
{

    return id < cmpx.id;
}
bool CVATRegister::cancelCompany ( const string &taxID )
{
    Company cmp("", "", taxID);

    //auto itr = upper_bound(DCompany.begin(), DCompany.end(), cmp); THIS NOT WORK
    auto itr = find(DCompany.begin(), DCompany.end(), cmp);  

    if(itr != DCompany.end())
     {   
        DCompany.erase(itr);
        sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
        { 
            return a.getId() < b.getId(); 
        });
        return true;
     }
     
     return false;
}

CodePudding user response:

You can use lower_bound to find and then compare with taxID

Like this:

bool CVATRegister::cancelCompany(const string &taxID)
{
    Company cmp("", "", taxID);

    auto itr = lower_bound(DCompany.begin(), DCompany.end(), cmp); 
    //auto itr = find(DCompany.begin(), DCompany.end(), cmp);

    if (itr != DCompany.end() && itr->getId() == taxID) {
        DCompany.erase(itr);
        sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b) {
            return a.getId() < b.getId();
        });
        return true;
    }

    return false;
}

CodePudding user response:

If DCompany is sorted with respect to Company::operator< (i.e. with respect to the company tax ID), then you can do:

bool CVATRegister::cancelCompany ( const string &taxID )
{
    Company const cmp("", "", taxID);
    
    auto const itr = lower_bound(DCompany.begin(), DCompany.end(), cmp);
    if(itr != DCompany.end() && itr->getId() == taxId)
    {   
        DCompany.erase(itr);

        // 1. No need to pass a lamda to sort your container again,
        //    since your Company::operator< will be called.
        // 2. No need to sort again your container after removing an
        //    element: it will already be sorted.
        //sort(DCompany.begin(), DCompany.end(), [](const Company & a, const Company & b)
        //{ 
        //    return a.getId() < b.getId(); 
        //});

        return true;
     }
     
     return false;
}
  • Related