You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++遍历map时,能否从非begin()的索引/键位置启动迭代器?

当然可以从非begin()的位置启动map迭代器!

完全没问题——你不仅能从begin()之外的位置启动迭代器,而且这在你的城市距离计算场景里,还能帮你避免重复计算,直接把计算量砍半,效率拉满。

你想构建的map<string, map<string, double>> dist本质是要存储城市间的双向距离,但城市A到B的距离和B到A是完全一样的,没必要计算两次。这时候从当前元素的下一个位置开始遍历第二个迭代器,就完美解决了重复问题。

具体实现代码示例

假设你的原始城市map是map<string, City>,下面是完整的实现思路:

#include <map>
#include <string>

// 假设你的City类和calc_dist函数已定义
class City { /* 包含坐标等成员 */ };
double calc_dist(const City& c1, const City& c2) { /* 计算两点距离的逻辑 */ }

int main() {
    map<string, City> cities = {
        {"Beijing", City{/* 坐标参数 */}},
        {"Shanghai", City{/* 坐标参数 */}},
        {"Guangzhou", City{/* 坐标参数 */}}
        // 更多城市...
    };

    map<string, map<string, double>> dist;

    // 遍历第一个城市的迭代器
    for (auto it1 = cities.begin(); it1 != cities.end(); ++it1) {
        // 从it1的下一个元素开始遍历第二个城市,避免重复计算
        auto it2 = next(it1); // C++11及以上可用,旧标准可以写成auto it2 = it1; ++it2;
        for (; it2 != cities.end(); ++it2) {
            double distance = calc_dist(it1->second, it2->second);
            // 双向赋值,让两种索引方式都能拿到结果
            dist[it1->first][it2->first] = distance;
            dist[it2->first][it1->first] = distance;
        }
    }

    // 测试使用
    double bj_to_sh = dist["Beijing"]["Shanghai"];
    double sh_to_bj = dist["Shanghai"]["Beijing"];
    // 两者值完全相同,且只计算了一次
    return 0;
}

额外技巧:从指定键的位置开始遍历

如果你需要从某个特定城市(比如指定键)开始遍历,也可以用find()拿到对应的迭代器,再从那里启动遍历:

auto start_city = cities.find("Shanghai");
if (start_city != cities.end()) {
    // 从Shanghai开始遍历后面的所有城市
    for (auto it = start_city; it != cities.end(); ++it) {
        // 处理逻辑...
    }
}

这种方式既满足了你的需求,又最大化了效率,完美适配你的二维距离map场景~

内容的提问来源于stack exchange,提问作者Grogie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:17:44