在下面for
循环,我测试查询中的字母是否在 unordered_map<string, int>
中.如果不是,我打印出一些东西。
queries = [ ["a", "c"], ["b", "a"], ["a", "e"], ["a", "a"], ["x", "x"] ]
for (vector<string>& q : queries) {
int start = index[q[0]], end = index[q[1]];
if (index.find("z") == index.end()) {cout << "z" << '\n';
}
index
仅包含 a, b, c
.相应地,输出是这样的:z z z z z
Which it should be, because one of the queries has an z
in it. Printing the size of index
gives 3.
However, if I run this:
for (vector<string>& q : queries) {
int start = index[q[0]], end = index[q[1]];
if (index.find(q[0]) == index.end()) {cout << "z" << '\n';
}
我没有得到任何输出,但我希望输出 x
因为那不在 index
.为什么是这样?
最佳答案
根据运营商[]
的描述cppreferance 中的 map :
Returns a reference to the value that is mapped to a key equivalent to key, performing an insertion if such key does not already exist.
index[q[0]]
创建了 key "x"
的条目.
关于C++将字符串传递给映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63256218/