Dess
Dess

Reputation: 77

Efficiency of std::tuple and std::map

I am currently building a program that relies on multiple vectors and maps to retain previously computed information. My vectors are of the standard format, and not very interesting. The maps are of the form

std::map<std::string, long double> 

with the intent of the string being a parseable mapping of one vector onto another, such as

std::map<std::string, long double> rmMap("fvProperty --> fvTime", 3.0234);

where I can later on split the string and compare the substrings to the vector names to figure out which ones were involved in getting the number. However, I have recently found that std::tuple is available, meaning I can skip the string entirely and use the vector positions instead with

std::tuple<unsigned int, unsigned int, long double>

This allows me (as far as I can tell) to use both the first and the second value as a key, which seems preferable to parsing a string for my indices.

My crux is that I am unaware of the efficiency here. There will be a lot of calls to these tuples/maps, and efficacy is of the essence, as the program is expected to run for weeks before producing an end result.

Thus, I would ask you if tuples are more or equally efficient (in terms of memory, cache, and cycles) than maps when it comes to large and computationally intense programs.

EDIT: If tuples cannot be used in this way, would the map

std::map<std::pair<unsigned int, unsigned int>, long double>

be an effective substitute to using strings for identification?

Upvotes: 2

Views: 11154

Answers (2)

Arne Mertz
Arne Mertz

Reputation: 24606

Tuples and Maps are used for very different purposes. So it should be primarily about what you want to use them for, not how efficient they are. You'll have some trouble to turn on your car with a screw driver, as you will have trying to fix a screw with your car keys. I'd advice against both.

A tuple is one little dataset, in your case e.g. the set {1,2,3.0234}. A map is for mapping multiple keys to their values. In fact, a map internally consists of multiple tuples (pairs), each one containing a key and the associated value. Inside the map, the pairs are arranged in a way that makes searching for the keys easy.

In your case, I'd prefer the map<pair<int, int>, double> as your edit suggests. The keys (i.e. the vector index pairings) are much easier to search for and "parse" than those strings.

Upvotes: 1

Jery
Jery

Reputation: 576

The advantage of the map is to efficiently query data associated to a key.

It cannot be compared to tuples which just pack values together: you will have to travel tuples yourself to retrieve the correct value.

Using a map<pair<unsigned int, unsigned int>, long double> as Mike suggests is probably the way to go.

Upvotes: 4

Related Questions