The lower_bound function of algorithms library takes a forward iterator and returns the lower bound. It works fine for vectors but when i used it for a map, I got compiler error. My doubt is that std::map supports bidirectional iterators which can obviously act as forward iterators, so why std::lower_bound(map.begin(),map.end(),int value) doesn't work but the member function of map class, map.lower_bound(int value) works for a map? Here is some example code for reference
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<int>v = {1,1,1,2,3,4,2,3,2,5,6,12,12,9};
map<int,int>mp;
for(auto x:v)mp[x]++;
for(int i=0;i<15;i++){
auto it = mp.lower_bound(i); // this works
// auto it = lower_bound(mp.begin(),mp.end(),i) //this doesn't work
if(it!=mp.end())
cout<<i<<" lower bound is "<<it->first<<" and its frequency in vector is "<<it->second<<endl;
}
return 0;
}
Everything you need can be found in the documentation
std::lower_boundexpects a sorted range of N values of typeTgiven by the iterators andTvalue to search for.N.std::map<Key,Value>::lower_boundexpectsKeykey to search for and the complexity is logarithmic inNbecause it performs binary search on the red-black tree, although that is technically an implementation detail.So,
std::lower_bounddoes not work for you because the map containspair<const Key,Value>, not justKey, the following will workbut the complexity is linear and of course it is not very useful if you only want to search using keys.
std::map::lower_boundsolves both problems. Although the latter could have been solved by customComparefunction.This pattern is common to all containers and algorithms, there is e.g. generic
std::findand specializedcontainer::findfor each container that is better.Please, do not use
#include<bits/stdc++.h>.