在地图上使用迭代器
Using iterators on maps
map<double, LatLon> closestPOI;
map<double, LatLon> ::iterator iterPOI = closestPOI.begin();
我制作了一棵以两点之间的距离作为键控的树。我需要找到这棵树中最小的 3 个点(3 个最小距离)。我声明了一个迭代器并将其初始化为指向根(我不确定这是否有必要,但它没有解决我的问题)。我尝试使用 advance(iterPOI, 1) 来增加迭代器,但这也不起作用。我怎样才能找到这 3 个点并访问它们的值?
注意:是的,我知道我想要的 3 个节点是根节点及其子节点(因为它们的距离最小)
通常您使用 for()
循环来迭代地图:
for(map<double, LatLon> ::iterator iterPOI = closestPOI.begin();
iterPOI != closestPOI.end();
++iterPOI) {
// access the iterator's key: iterPOI->first ...
// access the iterator's value: iterPOI->second ...
}
要遍历地图,您可以这样做:(假设您使用的是 gcc 4.8.2 之上的任何东西)
map<double, LatLon> closestPOI;
// if you don't have gcc 4.8.2 then do what you did with the iterator in your question...
for(auto i_poi = closestPOI.begin(); i_poi != closestPOI.end(); ++i)
{
// to get at the double you do: i_poi->first
// to get at the LatLon you do: i_poi->second
}
希望有点帮助
这里是获取地图的前三个(即最小键)元素的示例。我将 LatLong
别名为 int
作为示例,所以 you can see it in action here:
#include <iostream>
#include <map>
#include <vector>
using LatLon = int;
int main()
{
std::map<double, LatLon> map { { 1.0d, 1 }, { 2.0d, 2 }, { 3.0d, 3 }, { 0.5d, 4 } };
// Get the three closest points and store them in a vector
std::vector<LatLon> closest;
for ( const auto& pair : map ) {
if ( closest.size() >= 3 )
break;
closest.push_back(pair.second);
}
// Do something with the three closest points
for ( auto latlon : closest )
std::cout << latlon << '\n';
return 0;
}
请注意,如果您的地图开始时少于 3 个点,则您的 closest
向量也将少于 3 个元素。
map<double, LatLon> closestPOI;
map<double, LatLon> ::iterator iterPOI = closestPOI.begin();
我制作了一棵以两点之间的距离作为键控的树。我需要找到这棵树中最小的 3 个点(3 个最小距离)。我声明了一个迭代器并将其初始化为指向根(我不确定这是否有必要,但它没有解决我的问题)。我尝试使用 advance(iterPOI, 1) 来增加迭代器,但这也不起作用。我怎样才能找到这 3 个点并访问它们的值?
注意:是的,我知道我想要的 3 个节点是根节点及其子节点(因为它们的距离最小)
通常您使用 for()
循环来迭代地图:
for(map<double, LatLon> ::iterator iterPOI = closestPOI.begin();
iterPOI != closestPOI.end();
++iterPOI) {
// access the iterator's key: iterPOI->first ...
// access the iterator's value: iterPOI->second ...
}
要遍历地图,您可以这样做:(假设您使用的是 gcc 4.8.2 之上的任何东西)
map<double, LatLon> closestPOI;
// if you don't have gcc 4.8.2 then do what you did with the iterator in your question...
for(auto i_poi = closestPOI.begin(); i_poi != closestPOI.end(); ++i)
{
// to get at the double you do: i_poi->first
// to get at the LatLon you do: i_poi->second
}
希望有点帮助
这里是获取地图的前三个(即最小键)元素的示例。我将 LatLong
别名为 int
作为示例,所以 you can see it in action here:
#include <iostream>
#include <map>
#include <vector>
using LatLon = int;
int main()
{
std::map<double, LatLon> map { { 1.0d, 1 }, { 2.0d, 2 }, { 3.0d, 3 }, { 0.5d, 4 } };
// Get the three closest points and store them in a vector
std::vector<LatLon> closest;
for ( const auto& pair : map ) {
if ( closest.size() >= 3 )
break;
closest.push_back(pair.second);
}
// Do something with the three closest points
for ( auto latlon : closest )
std::cout << latlon << '\n';
return 0;
}
请注意,如果您的地图开始时少于 3 个点,则您的 closest
向量也将少于 3 个元素。