迭代向量对

新手上路,请多包涵

我已经编写了以下代码片段,但它似乎不起作用。

 int main(){
    int VCount, v1, v2;
    pair<float, pair<int,int> > edge;
    vector< pair<float, pair<int,int> > > edges;
    float w;
    cin >> VCount;
    while( cin >> v1 ){
        cin >> v2 >> w;
        edge.first = w;
        edge.second.first = v1;
        edge.second.second = v2;
        edges.push_back(edge);
    }
    sort(edges.begin(), edges.end());
    for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; itt != edges.end; it++){
        cout >> it.first;
    }
    return 0;
}

它在包含 for 循环的行中引发错误。错误是:

 error: no match for ‘operator<’ in ‘it < edges.std::vector<_Tp, _Alloc>::end [with _Tp = std::pair<float, std::pair<int, int> >, _Alloc = std::allocator<std::pair<float, std::pair<int, int> > >, std::vector<_Tp, _Alloc>::const_iterator = __gnu_cxx::__normal_iterator<const std::pair<float, std::pair<int, int> >*, std::vector<std::pair<float, std::pair<int, int> > > >, typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::const_pointer = const std::pair<float, std::pair<int, int> >*]

谁能帮我吗?

原文由 Peeyush 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 607
2 个回答

循环中至少有三个错误。

 for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; itt != edges.end; it++){
        cout >> it.first;
    }

首先,您必须使用 edges.end() 而不是 edges.end 。身体内部必须有

    cout << it->first;

代替

    cout >> it.first;

为了避免此类错误,您可以简单地编写

for ( const pair<float, pair<int,int> > &edge : edges )
{
   std::cout << edge.first;
}

原文由 Vlad from Moscow 发布,翻译遵循 CC BY-SA 3.0 许可协议

C++14 迭代器要简单得多

for (const auto& pair : edges)
{
    std::cout << pair.first;
}

C++17 迭代器允许更深入的访问

for (const auto& [first, sec] : edges)
{
    std::cout << first;
}

原文由 J‘e 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题