從這裡來的文章 :
sample :
template< typename MapType, // type of map
typename KeyArgType, // type of Key
typename ValueArgtype> // type of Value
typename MapType::iterator efficientAddOrUpdate(MapType& m,
const KeyArgType& k,
const ValueArgtype& v)
{
//find where k is or should be
typename MapType::iterator Ib = m.lower_bound(k);
if ( Ib != m.end() && // if Ib points to a pair
!(m.key_comp()(k, Ib->first)))
{ // whose key is equivalent to k...
Ib->second = v; // update the pair's value
return Ib; // and return an iterator to that pair
}else {
typedef typename MapType::value_type MVT;
// add pair(k, v) to m and return an iterator
// to the new map element
return m.insert(Ib, MVT(k, v));
}
}
int main()
{
map<int,int> m1 ;
for(int idx=0;idx<10;idx++)
{
pair<map<int,int>::iterator,bool> px ;
px = m1.insert(std::map<int,int>::value_type(idx,idx)) ;
if(px.second == false)
{
cout << "1:"<< idx << " existed,val=" << px.first->second << endl ;
}
px = m1.insert(std::map<int,int>::value_type(idx,idx*idx)) ;
if(px.second == false)
{
cout << "2:"<< idx << " existed,val=" << px.first->second << endl ;
}
}
for(int idx=0;idx<10;idx++)
cout << m1[idx] << " " ;
cout << endl ;
map<int,int> m2 ;
for(int idx=0;idx<10;idx++)
{
efficientAddOrUpdate(m2,idx,idx) ;
efficientAddOrUpdate(m2,idx,idx*idx) ;
}
for(int idx=0;idx<10;idx++)
cout << m2[idx] << " " ;
cout << endl ;
}
2:0 existed,val=0
2:1 existed,val=1
2:2 existed,val=2
2:3 existed,val=3
2:4 existed,val=4
2:5 existed,val=5
2:6 existed,val=6
2:7 existed,val=7
2:8 existed,val=8
2:9 existed,val=9
0 1 2 3 4 5 6 7 8 9
0 1 4 9 16 25 36 49 64 81
留言列表