C++将字符串传递给映射

标签 c++ string unordered-map

在下面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/

相关文章:

c++ - valgrind 检查简单的多线程 c++11 得到 sig11 错误

c++ - glGetShaderInfoLog 到 std::string?

c++ - std::unordered_map 上的线程安全包装器

c++ - 我可以同时调用 std::unordered_map 的这些成员函数吗?

c++ - 十进制奇偶校验

c++ - 后期绑定(bind)有什么优点?举一个 C++ 函数指针上下文中的例子

c# - 比较两个不同顺序的字符串

string - 如何将 float 转换为字符串

c++ - 无序 map 不打印所有存储桶值

c++ - 在 C++ 中没有匹配的调用函数