Vivek Goel Vivek Goel - 1 month ago 4x
C++ Question

Access elements of map which is member of vector without creating copy

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:


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?


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