1

I have following data type

typedef     std::map <std::string.std::string> leaf; 
typedef     std::map <std::string,leaf> child;
typedef     std::vector<child> parent;

Now if I want access parent element at index 0 and child element having key "x" and then perform some operation of it's values

First way of doing this will be like:

    parentobject[0]["x"]["r"]

But every time I need to repeat these index whenever I want access that value.

Second way of doing this will be like: std::string value=parentobject[0]["x"]["r"] Then use value object. But problem with this approach is this line will create copy of the string.

Is there a better way to access variable without creating copy?

Vivek Goel
  • 22,942
  • 29
  • 114
  • 186

2 Answers2

2

You can use reference to avoid copy:

std::string & value = parentobject[x][y][z]; 

Or, will you be okay with this instead:

//define a lambda in the scope
auto get =  [] (int x, std::string const & y, std::string const & z) 
      -> std::string &
{
    return parentobject[x][y][z];
}

//then use it as many times as you want in the scope
std::string & value = get(0, "x", "r");

get(1, "y", "s") = "modify";
Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • What's the value of that function, aside from potentially adding the overhead of a function call? You still have to specify all the arguments and all you've done is hidden the object they're looked-up from. – Lightness Races in Orbit Dec 15 '12 at 20:32
  • @LightnessRacesinOrbit: Nothing great, just doing the same thing differently, some people like it. And a little advantage you have here : you can easily change the name `parentobject` to `grandparentobject` when the project gets too old. – Nawaz Dec 15 '12 at 20:34
  • @VivekGoel: Any problem with my answer? – Nawaz Dec 15 '12 at 20:50
  • @Nawaz I think first answer was having problem. In that function was assuming name of parentobject and it's scope. – Vivek Goel Dec 15 '12 at 20:56
2

Use a reference:

const std::string& value = parentobject[0]["x"]["r"];

Now you can refer to value anywhere you like (within the same block scope) without having to perform the map lookups again.

Remove the const if you really need to.

Please purchase and read one of these books in order to learn C++'s basic features.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055