;: दक्षता मामलों में अंतर, तो आप इस तरह अपने ट्रेवर्सल संरचना कर सकते हैं
typedef std::map< KeyType, std::list<ValueType> > MapKeyToMultiValue;
निवेशन, और अधिक मुश्किल होगा लेकिन अगर आप डुप्लिकेट प्रविष्टियों के साथ परेशान करने के लिए बिना सभी चाबियाँ पर पुनरावृति कर सकते हैं। प्रविष्टि के रूप में विचार करेंगे इस प्रकार है:
void insert_m(MapKeyToMultiValue &map, const KeyType key, const ValueType value)
{
auto it = map.find(key);
if (it == map.end())
{
std::list<ValueType> empty;
std::pair< MapKeyToMultiValue::iterator, bool > ret =
map.insert(MapKeyToMultiValue::value_type(key, empty));
it = ret.first;
}
it->second.push_back(value);
}
या आपको लगता है कि बहुत टेम्प्लेटेड बना सकते हैं:
#include <map>
#include <list>
#include <string>
#include <stdio.h>
typedef std::string KeyType;
typedef int ValueType;
typedef std::map< KeyType, std::list<ValueType> > MapKeyToMultiValue;
void insert_m(MapKeyToMultiValue &map, const KeyType key, const ValueType value)
{
auto it = map.find(key);
if (it == map.end())
{
std::list<ValueType> empty;
std::pair< MapKeyToMultiValue::iterator, bool > ret =
map.insert(MapKeyToMultiValue::value_type(key, empty));
it = ret.first;
}
it->second.push_back(value);
}
template<typename KeyType, typename ValueType,
typename MapType = std::map< KeyType, std::list<ValueType> > >
void insert_multi(MapType &map, const KeyType key, const ValueType value)
{
auto it = map.find(key);
if (it == map.end())
{
std::list<ValueType> empty;
std::pair< typename MapType::iterator, bool > ret =
map.insert(typename MapType::value_type(key, empty));
it = ret.first;
}
it->second.push_back(value);
}
int main()
{
MapKeyToMultiValue map;
insert_m(map, std::string("aaa"), 1);
insert_m(map, std::string("aaa"), 2);
insert_m(map, std::string("bb"), 3);
insert_m(map, std::string("cc"), 4);
insert_multi(map, std::string("ddd"), 1);
insert_multi(map, std::string("ddd"), 2);
insert_multi(map, std::string("ee"), 3);
insert_multi(map, std::string("ff"), 4);
for(auto i = map.begin(); i != map.end(); ++i)
{
printf("%s\n", i->first.c_str());
}
return 0;
}
लेकिन सामान्य ओ (एन) ट्रैवर्सल के बजाए ओ (एन लॉग एन) जटिलता के लिए क्या हुआ, जैसा कि @ user3701170 के उत्तर में उल्लिखित है। – ddevienne
@ddevienne दुख की बात है, आजकल हर कोई प्रदर्शन पर लालित्य चुनता है। – GreenScape