Using packed_trie_map directly¶
In the previous example, we showed a way to create an instance of packed_trie_map
from a populated instance of trie_map. There is also a way
to instantiate and populate an instance of packed_trie_map
directly, and that is what we will cover in this section.
First, declare the type:
using trie_map_type = mdds::packed_trie_map<std::string, int>;
Once again, we are using std::string as its key, and int as its value
type. The next step is to prepare its entries ahead of time:
trie_map_type::entry entries[] =
{
{ MDDS_ASCII("Apex"), 42214 },
{ MDDS_ASCII("Asheville"), 87236 },
{ MDDS_ASCII("Burlington"), 51510 },
{ MDDS_ASCII("Cary"), 151088 },
{ MDDS_ASCII("Chapel Hill"), 59635 },
{ MDDS_ASCII("Charlotte"), 792862 },
{ MDDS_ASCII("Concord"), 83506 },
{ MDDS_ASCII("Durham"), 245475 },
{ MDDS_ASCII("Fayetteville"), 204408 },
{ MDDS_ASCII("Gastonia"), 73209 },
{ MDDS_ASCII("Goldsboro"), 36306 },
{ MDDS_ASCII("Greensboro"), 279639 },
{ MDDS_ASCII("Greenville"), 89130 },
{ MDDS_ASCII("Hickory"), 40361 },
{ MDDS_ASCII("High Point"), 107741 },
{ MDDS_ASCII("Huntersville"), 50458 },
{ MDDS_ASCII("Jacksonville"), 69079 },
{ MDDS_ASCII("Kannapolis"), 44359 },
{ MDDS_ASCII("Raleigh"), 431746 },
{ MDDS_ASCII("Rocky Mount"), 56954 },
{ MDDS_ASCII("Wilmington"), 112067 },
{ MDDS_ASCII("Wilson"), 49628 },
{ MDDS_ASCII("Winston-Salem"), 236441 },
};
We need to do this since packed_trie_map is immutable, and
the only time we can populate its content is at instantiation time. Here, we
are using the MDDS_ASCII macro to expand a string literal to its
pointer value and size. Note that you need to ensure that the entries are sorted
by the key in ascending order.
Warning
When instantiating packed_trie_map directly with a static
set of entries, the entries must be sorted by the key in ascending order.
You can then pass this list of entries to construct the instance:
trie_map_type nc_cities(entries, std::size(entries));
Once it’s instantiated, the rest of the example for performing searches will be the same as in the previous section, which we will not repeat here.
The complete source code for the example in this section is available here.