我有以下数据类型
typedef std::map <std::string.std::string> leaf;
typedef std::map <std::string,leaf> child;
typedef std::vector<child> parent;
现在,如果我想访问索引为 0 的父元素和具有键“x”的子元素,然后对其值执行一些操作
第一种方法如下:
parentobject[0]["x"]["r"]
但是每当我想访问该值时,我都需要重复这些索引。
第二种方法是: std::string value=parentobject[0]["x"]["r"] 然后使用值对象。但这种方法的问题是这一行将创建字符串的拷贝。
有没有更好的方法来访问变量而不创建拷贝?
最佳答案
您可以使用引用来避免复制:
std::string & value = parentobject[x][y][z];
或者,你能接受这个吗:
//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";
关于c++ - 在不创建拷贝的情况下访问作为 vector 成员的 map 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13895828/