Associative (dictionary-like) containers such as QMap
and std::map
rarely provide sequential indexing as internally they are typically implemented as tree-like data structures (for example, Red-Black Tree).
Notable exception is boost's flat_map
. It is implemented as a pair of contiguous arrays, where mapping of the key and value is expressed with array indices: mapped key and value have the same index. flat_map
provides method nth()
to access value by index:
boost::container::flat_map<std::string, float> geek_numbers;
geek_numbers.emplace("pi", 3.14f);
geek_numbers.emplace("e", 2.72f);
geek_numbers.emplace(
"Answer to the Ultimate Question of Life, The Universe, and "
"Everything",
42.0f);
auto 0th = geek_numbers.nth(0); // 42.0f
auto 1st = geek_numbers.nth(1); // 2.72f
auto 2nd = geek_numbers.nth(2); // 3.14f
flat_map
"emulates" interface and behavior of the std::map
and sorts elements by key. You can use custom predicates.
Note that standard containers are suitable only for simplest database-like usecases. In general, databases is a very complicated topic. There are entire theories being built about it. If your dataset is large and you need to perform complicated indexing and queries, think about embedding one of the database engines available (e.g. SQLite, or other, more heavyweight ones).