Search code examples
c++vectorlower-bound

Insert into a vector using an insert using lower_bound


How do I change CompareByNA to make the insert work, I assume it's wrong for the first element to insert program: https://onecompiler.com/cpp/3xycp2vju

bool Company::compareByNA(const Company &a, const Company &b)
{
    return a.getNameAddr() < b.getNameAddr();
}
..
if ( binary_search(CompanyNameList.begin(), CompanyNameList.end(), cmp, Company::compareByNA) )
    {       
        CompanyNameList.insert(lower_bound(CompanyNameList.begin(), CompanyIDList.end(), cmp, Company::compareByNA), cmp); 
        return true;
    }
    return false;
}

for example this not work for other elements that I want to insert in order

if(CompanyNameList.size() == 0)
   {
        CompanyNameList.push_back(cmp);
        return true;
   }

Solution

  • Here is your issue

    lower_bound(CompanyNameList.begin(), CompanyIDList.end(), cmp, Company::compareByNA); 
    

    You are mixing up your lists. You probably meant to use

    lower_bound(CompanyNameList.begin(), CompanyNameList.end(), cmp, Company::compareByNA);