MM1*_*MM1 5 c++ indexing vector
如标题所述,我试图在成对的向量中找到元素的索引。我有以下向量:std::vector<std::pair<std::string, double>> dict。我的字典的内容是:
Name1 11
Name2 9
Name3 10
Name4 12
Name5 13
Run Code Online (Sandbox Code Playgroud)
所有我在为了找到该指数是first的属性pair。例如我有Name5并且我想找到 4。(因为Name5是第五个元素)。有谁知道该怎么做?我尝试了一些东西,但似乎不起作用:
auto it = std::find(dict.begin(), dict.end(), movieName);
Run Code Online (Sandbox Code Playgroud)
哪里movieName是std::stringwith"Name5"里面。谢谢!
您可以使用谓词来决定向量中的哪些条目应该匹配。使用 lambda 实现这一点最简单:
auto it = std::find_if(dict.begin(), dict.end(),
[&](const auto& pair) { return pair.first == movieName; });
Run Code Online (Sandbox Code Playgroud)
拥有迭代器后,将其进行比较以dict.end()查看是否存在任何匹配,如果存在匹配,您可以使用 std::distance() 将其转换为向量的索引,如 d4rk4ng31 在问题下评论的那样。
我会简单地使用正常的 for_each 循环。
所以:
int index = 0;
for(const auto& pair : dict) {
if(pair.first == <whatever>) {
break;
}
index++;
}
//if index == dict.size() then print element not found
Run Code Online (Sandbox Code Playgroud)
其他方法是使用 std::find_if() (感谢@Tony Delroy :))
auto index = std::distance(dict.begin(), std::find_if(dict.begin(), dict.end(), [&](const auto& pair) { return pair.first == movieName; }));
Run Code Online (Sandbox Code Playgroud)