持有对多重嵌套 std::vector 的引用的正确内容是什么?

What is the correct what to hold a reference to a multiply nested std::vector?

我正在分析我们的应用程序,发现如下结构占用了大量时间:

void Locations::remove_without_set_index(Item *item) {
  locations[item->x()][item->y()][item->z()].back()->LocationIndexHandler::set_index(item->LocationIndexHandler::index());
  locations[item->x()][item->y()][item->z()][item->LocationIndexHandler::index()] = locations[item->x()][item->y()][item->z()].back();
  locations[item->x()][item->y()][item->z()].pop_back();
}

所以看起来合理的方法是获取一次引用然后使用它而不是多次调用它。但是,当我这样做时:

void Locations::remove_without_set_index(Item *item) {
  auto reference = locations[item->x()][item->y()][item->z()];
  reference.back()->LocationIndexHandler::set_index(item->LocationIndexHandler::index());
  reference[item->LocationIndexHandler::index()] = reference.back();
  reference.pop_back();
}

我最终遇到了分段错误和错误,例如损坏的双链表。数据结构定义如下:

std::vector<std::vector<std::vector<std::vector<Item*>>>> locations;

所以我假设我抓取的参考是不正确的。是否可以正确持有参考?如果可以,如何?

您的参考不是参考。这是一个副本。您需要这样做:

auto& reference = locations[item->x][item->y][item->z];
//  ^

C++ 默认是值语义的,你必须选择加入引用。

你好像忘记了这个表达式中的括号

auto reference = locations[item->x()][item->y()][item->z()];
                                  ^^         ^^         ^^

或这样的声明

locations[item->x()][item->y()][item->z()].back()->LocationIndexHandler::set_index(item->LocationIndexHandler::index()); 

不带括号。

无论如何你也可以使用下面的方法来定义引用

decltype( auto ) reference = ( locations[item->x()][item->y()][item->z()] );