此题的解答有很多种,其中一种在结束前我就想到,但是没有能解出来。因为一些细节的C++问题。
解法主要思路是使用一个 map<long long, list<int>::iterator>
问题 1 map 取到的值是什么?
如果键存在,没什么好说的。
如果键不存在,使用[] 访问的话
TL;DR 调用构造函数构建默认值
如果使用 std::map<Key,T,Compare,Allocator>::at,不存在则将抛出异常。
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <stdexcept>
using namespace std;
class Test {
public:
Test() { puts("Object constructed"); }
};
int main() {
map<int, Test> m;
m[35];
try {
m.at(36);
} catch (out_of_range) {
puts("not exist");
}
return 0;
}
将返回
Object constructed not exist
问题 2 list<int>::iterator 的默认值是什么?
悬挂
这个问题是在我没有处理好问题 1 的时候提出来的,正常人都不会这么干
Reference
本作品使用基于以下许可授权:Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
