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

如何用迭代器访问vector中的嵌套pair?代码报错求解决

问题排查与代码修正

我帮你梳理了代码里的编译错误和逻辑问题,这些应该就是Code::Blocks报错的根源:

1. 基础语法与拼写错误

  • using namestace std; 里的namestace是拼写错误,应该改成namespace。
  • Q.push(s) 语句末尾缺少分号,C++语句必须以分号结尾。
  • while(!Q.empty() 缺少右括号,正确写法是while(!Q.empty())。

2. 迭代器访问逻辑错误

你的it->second是一个pair<int, bool>对象,不是指针类型,所以不能用->访问它的成员,应该用.。原代码里的it->second->first要改成it->second.first。

3. 代码结构不完整

你的代码末尾缺少多个闭合大括号,导致编译时无法识别代码块边界:

  • 闭合if语句的}
  • 闭合for循环的}
  • 闭合while循环的}
  • 闭合BFS函数的}

修正后的完整代码

#include<bits/stdc++.h>
using namespace std;

vector<pair<int , pair<int, bool> > > graph[1000000];
vector<pair<int , pair<int, bool> > >:: iterator it;
queue<int> Q;
int cost[1000000], visit[1000000];

void BFS(int s) {
    Q.push(s);
    visit[s] = 1;
    // 可以在这里初始化cost数组为-1,确保BFS的判断逻辑生效
    memset(cost, -1, sizeof(cost));
    cost[s] = 0; // 起点的成本设为0
    while(!Q.empty()) {
        int v = Q.front();
        Q.pop();
        for (it=graph[v].begin(); it != graph[v].end(); it++) {
            if(cost[it->first] == -1) {
                cost[it->first] = it->second.first + cost[v];
                Q.push(it->first);
            }
        }
    }
}

额外提个小建议:全局数组cost默认初始值是0,如果你需要用cost[xxx] == -1来判断未访问节点,最好手动初始化数组,我已经在修正后的代码里加上了相关逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:59:03