当我运行以下代码时,我在“find()”调用中遇到了段错误。
#include <vector>
#include <unordered_map>
struct item {
std::unordered_map<int,int> map;
};
int main(int argc, char** argv) {
std::vector<item> stack;
stack.emplace_back();
std::unordered_map<int,int>& topmap=stack.back().map;
stack.emplace_back();
auto ind=topmap.find(5);
if(ind!=topmap.end()) {
printf("Found element five in second to top item\n");
}
}
(使用 -std=c++11 编译)
但是,如果删除了第二个 emplace_back() 调用,则没有段错误。
为什么是这样?我是否使用了错误的参考变量?向堆栈中添加另一个元素是否会使 topmap 无效?