Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. May 14, 2014 #1
    Is there a better way to do what I'm trying to do?

    Code (Text):

    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: May 14, 2014
  2. jcsd
  3. May 14, 2014 #2

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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 (Text):
    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 (Text):
    const std::map<std::string, std::string> derivMap =
       { {"x", "1"}, {"sin(x)", "cos(x)"} };
     
  4. May 14, 2014 #3
    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.
     
  5. May 14, 2014 #4

    D H

    User Avatar
    Staff Emeritus
    Science Advisor

    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).
     
  6. May 14, 2014 #5
    The concepts I follow are

    RTW (Reinvent the Wheel)

    and

    STOMO (Spend Time on Micro Optimizations)
     
  7. May 15, 2014 #6

    SixNein

    User Avatar
    Gold Member

    You should probably refactor your code.

    Code (Text):

    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 (Text):

    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)")
    };

     
     
  8. May 15, 2014 #7

    SixNein

    User Avatar
    Gold Member

    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C++: Is there a better way to initialize a vector of pairs?
  1. C++ Vectors (Replies: 1)

Loading...