And if you want to do both with one container, you can always use boost::multi_index :P
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/identity.hpp>
#include <boost/multi_index/member.hpp>
#include <functional>
#include <utility>
#include <iostream>
#include <string>
using namespace boost::multi_index;
class Dictionary
{
typedef std::pair<std::string, std::string> Pair;
struct ordered {};
struct hashed {};
typedef multi_index_container
<
Pair,
indexed_by
<
ordered_unique<tag<ordered>, identity<Pair> >,
hashed_unique <tag<hashed>, member<Pair, std::string, &Pair::first> >
>
> Container;
typedef Container::index<ordered>::type data_ordered;
typedef Container::index<hashed >::type data_hashed;
public:
void Insert(const std::string & english, const std::string & french)
{
data.get<ordered>().insert(Pair(english, french));
}
void PrintAll()
{
data_ordered::const_iterator cur_it = data.get<ordered>().begin();
data_ordered::const_iterator end_it = data.get<ordered>().end();
for (; cur_it != end_it; ++cur_it)
{
std::cout
<< cur_it->first << " -> "
<< cur_it->second << std::endl;
}
}
std::string Find(const std::string & english)
{
data_hashed::const_iterator it;
it = data.get<hashed>().find(english, boost::hash<std::string>(), std::equal_to<std::string>());
if (it != data.get<hashed>().end())
return english + " -> " + it->second;
else
return english + " not found...";
}
private:
Container data;
};
int main()
{
Dictionary dictionary;
dictionary.Insert("hi", "salut");
dictionary.Insert("dog", "chien");
dictionary.Insert("god", "dieu" );
dictionary.Insert("blue", "bleue");
dictionary.PrintAll();
std::cout << std::endl;
std::cout << dictionary.Find("hi") << std::endl;
std::cout << dictionary.Find("hello") << std::endl;
}; Output:
blue -> bleue
dog -> chien
god -> dieu
hi -> salut
hi -> salut
hello not found... m4ster_r0shi
Posting Whiz in Training
283 posts since Mar 2010
Reputation Points: 172
Solved Threads: 41
Skill Endorsements: 2