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

C++使用STL vector存储带权图打印pair值编译报错求助

C++ 带权图vector存储问题修正

错误原因

  1. adj[i]的元素类型为pair<int,int>,使用int j接收会出现类型不匹配错误
  2. C++标准库未提供pair类型的cout直接输出重载,即使类型匹配也无法直接打印
  3. 原代码中vector<pair<int,int>> adj[n+1];是C风格变长数组,不属于C++标准语法,可移植性差

错误代码段修改方案

将出错的循环部分替换为如下代码:

for(int i = 1; i <= n; i++)
{
    // 使用auto自动推导元素类型为pair<int,int>
    for(auto &edge : adj[i])
    {
        // edge.first为邻接顶点编号,edge.second为边权重
        cout << i << " -> " << edge.first << "(权重:" << edge.second << ")" << endl;
    }
    cout << endl;
}

若要修复变长数组的兼容性问题,将原数组声明替换为标准嵌套vector即可:

vector<vector<pair<int,int>>> adj(n+1);

完整可运行修正代码

#include<iostream>
#include<vector>
using namespace std;
int main()
{
    int n,m,c;
    cout<<"Enter n,m : "<<endl;
    cin>>n>>m;
    vector<vector<pair<int,int>>> adj(n+1);
    cout<<"If un-directed input 1 else input 0: "<<endl;
    cin>>c;
    cout<<"Enter the values of u,v and the weight : "<<endl;
    for(int i=0;i<m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        adj[u].push_back({v,w});
        if(c==1)
            adj[v].push_back({u,w});
    }
    for(int i = 1; i <= n; i++)
    {
        for(auto &edge : adj[i])
        {
            cout<<i<<" -> " << edge.first << "(权重:" << edge.second << ")" <<endl;
        }
        cout<<endl;
    }
    cout<<"Inserted Successfully";
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:06:07