Warning: this is a crude manner of very desired behavior. This is not anywhere near good code, but it is quick and should demonstrate a technique for this.
, Boost multi_index
, . , , .
template<typename Key, typename Val>
class OrderedMap
{
private:
std::vector<std::pair<Key, Val>> ordered;
std::map<Key, std::size_t> lookup;
public:
void insert(Key k, Val v)
{
ordered.push_back(std::pair<Key, Val>(k, v));
lookup.emplace(k, ordered.size() - 1);
}
Val find(Key k)
{
std::size_t index = lookup[k];
return ordered[index].second;
}
typename std::vector<std::pair<Key, Val>>::iterator begin()
{
return ordered.begin();
}
typename std::vector<std::pair<Key, Val>>::iterator end()
{
return ordered.end();
}
};
, , std::vector<std::pair<Key, Val>>
, std::map<Key, std::size_t>
, . , , /.
, , , - , .
. .
OrderedMap<std::string, int> m;
m.insert("1", 1);
m.insert("2", 2);
m.insert("3", 3);
std::cout << m.find("2") << std::endl << std::endl;
for (auto i = m.begin(); i != m.end(); i++)
std::cout << i->first << " " << i->second << std::endl;
std::cout << std::endl;
:
2
1 1
2 2
3 3