C++: Is there a better way to initialize a vector of pairs?

  • Topic: C/C++ 
  • Thread starter Thread starter Jamin2112
  • Start date Start date
  • Tags Tags
    Vector
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
6 replies · 17K views
Jamin2112
Messages
973
Reaction score
12
Is there a better way to do what I'm trying to do?

Code:
const std::vector<std::pair<std::string, std::string>> derivMap =
   { std::make_pair("x", "1"), std::make_pair("sin(x)", "cos(x)") };

Seems kinda wordy.
 
Last edited by a moderator:
Physics news on Phys.org
The syntax you are using suggests you are using C++11. (That syntax was not legal in C++98/03.)

Given that, you can replace the std::make_pair(a,b) with {a,b}, which is much more compact.

Code:
const std::vector<std::pair<std::string, std::string>> derivMap =
   { {"x", "1"}, {"sin(x)", "cos(x)"} };

That said, why are you using a vector here? A map would seem to be the better choice:

Code:
const std::map<std::string, std::string> derivMap =
   { {"x", "1"}, {"sin(x)", "cos(x)"} };
 
D H said:
That said, why are you using a vector here? A map would seem to be the better choice

Isn't a map overkill if I'm only going to have 10 elements or so? That computation time for a binary search, plus the extra memory, would be useless when I could just iterate across 10 contiguous memory locations.
 
Overkill? No! It's the other way around. A map should make your code shorter and simpler. That's the number one goal in programming. There's a name for this concept, KISS (keep it short and simple).
 
D H said:
Overkill? No! It's the other way around. A map should make your code shorter and simpler. That's the number one goal in programming. There's a name for this concept, KISS (keep it short and simple).

The concepts I follow are

RTW (Reinvent the Wheel)

and

STOMO (Spend Time on Micro Optimizations)
 
Jamin2112 said:
Is there a better way to do what I'm trying to do?

Code:
const std::vector<std::pair<std::string, std::string>> derivMap =
   { std::make_pair("x", "1"), std::make_pair("sin(x)", "cos(x)") };

Seems kinda wordy.

You should probably refactor your code.

Code:
const std::vector<std::pair<std::string, std::string>> derivMap = { 
     std::make_pair("x", "1"), 
     std::make_pair("sin(x)", "cos(x)") 
};

you could also do something along the lines of

Code:
typedef std::pair<std::string, std::string> stringpair;

const std::vector<stringpair> derivMap = {
     std::make_pair("x", "1"), 
     std::make_pair("sin(x)", "cos(x)") 
};
 
D H said:
Overkill? No! It's the other way around. A map should make your code shorter and simpler. That's the number one goal in programming. There's a name for this concept, KISS (keep it short and simple).

From an algorithmic point of view, the setup of a red and black binary tree can be an expensive cost to pay for only a few elements.