英文:
map find the first non consecutive key
问题
我有一个以整数为键的地图。
使用STL,我想找到第一个具有非连续键的元素。
它应该是这样的:
map<int, int> m {
{1, 1},
{2, 2},
{3, 3},
{5, 5},
{6, 6},
{8, 8},
};
bool func(const pair<int, int>& a, const pair<int, int>& b){
return (a.first + 1) != b.first;
}
int main()
{
cout << find_first_of(m.begin(), m.end(), 1, func)->first; //gives 3
cout << find_first_of(m.begin(), m.end(), 2, func)->first; //gives 3
cout << find_first_of(m.begin(), m.end(), 5, func)->first; //gives 6
return 0;
}
我在STL中找不到任何可以执行这项任务的函数,是否可以提供帮助?
英文:
I have a map with integer as keys.
Using stl, I would like to find the first element that has not consecutive keys.
I should look like that:
map<int, int> m {
{1, 1},
{2, 2},
{3, 3},
{5, 5},
{6, 6},
{8, 8},
};
bool func(const pair<int, int>& a, const pair<int, int>& b){
return (a.first + 1) != b.first;
}
int main()
{
cout << find_first_of(m.begin(), m.end(), 1, func)->first; //gives 3
cout << find_first_of(m.begin(), m.end(), 2, func)->first; //gives 3
cout << find_first_of(m.begin(), m.end(), 5, func)->first; //gives 6
return 0;
}
I couldn't find any function doing this in stl, any help ?
答案1
得分: 1
你可以使用std::adjacent_find来搜索地图中连续的键。
以下是一个示例。
#include <map>
#include <iostream>
#include <algorithm>
std::map<int, int> m{
{1, 1},
{2, 2},
{3, 3},
{5, 5},
{6, 6},
{8, 8},
};
int main()
{
auto iter = std::adjacent_find(m.begin(), m.end(), [](cont auto& pr1, const auto& pr2)
{
return (pr1.first != pr2.first - 1);
});
if (iter != m.end())
{
std::cout << "The last consecutive element is {" << iter->first << ", " << iter->second << "}\n";
std::advance(iter, 1);
std::cout << "The first non-consecutive element is {" << iter->first << ", " << iter->second << "}\n";
}
else
std::cout << "All pairs are consecutive";
}
输出:
The last consecutive element is {3, 3}
The first non-consecutive element is {5, 5}
英文:
You can use std::adjacent_find to search consecutive keys in the map.
Here is an example.
#include <map>
#include <iostream>
#include <algorithm>
std::map<int, int> m{
{1, 1},
{2, 2},
{3, 3},
{5, 5},
{6, 6},
{8, 8},
};
int main()
{
auto iter = std::adjacent_find(m.begin(), m.end(), [](cont auto& pr1, const auto& pr2)
{
return (pr1.first != pr2.first - 1);
});
if (iter != m.end())
{
std::cout << "The last consecutive element is {" << iter->first << ", " << iter->second << "}\n";
std::advance(iter, 1);
std::cout << "The first non-consecutive element is {" << iter->first << ", " << iter->second << "}\n";
}
else
std::cout << "All pairs are consecutive";
}
Output:
The last consecutive element is {3, 3}
The first non-consecutive element is {5, 5}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论