nếu bạn phải vượt qua tất cả các khóa duy nhất một cách nhanh chóng thì bạn có thể sử dụng std :: map thay thế;
typedef std::map< KeyType, std::list<ValueType> > MapKeyToMultiValue;
Chèn sẽ khó khăn hơn, Tuy nhiên bạn có thể lặp qua tất cả các khóa mà không phải bận tâm đến các mục trùng lặp. Chèn sẽ trông như sau:
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);
}
hoặc bạn có thể làm cho điều đó rất templated:
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);
}
Các chương trình thử nghiệm đầy đủ trông như sau:
#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;
}
Nhưng những gì cho sự phức tạp O (n log n) này đòi hỏi, thay vì O (n) traversal bình thường, như đã đề cập trong câu trả lời của @ user3701170. – ddevienne
@ddevienne thật đáng buồn, ngày nay mọi người đều chọn sự thanh lịch hơn hiệu suất. – GreenScape