C++ 迭代对的向量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25606108/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 11:22:20  来源:igfitidea点击:

Iterate over vector of pair

c++vectorstliteratorconst-iterator

提问by Peeyush

I have written following code snippet but it does not seem to be working.

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

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;
}

It is throwing an error at the line containing for loop. The error is:

它在包含 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> >*]

Can anyone help me out?

谁能帮我吗?

回答by Vlad from Moscow

There are at least three errors in the loop.

循环中至少有三个错误。

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

First of all you have to use edges.end()instead of edges.end. And inside the body there has to be

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

    cout << it->first;

instead of

代替

    cout >> it.first;

To escape such errors you could write simply

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

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

回答by P0W

for ( vector < pair<float,pair<int,int>> >::const_iterator it = edges.begin() ; 

     it != edges.end () ;  // Use (), and assuming itt was a typo
     it++)
{
    cout << it->first; // Use -> 
}

Also, you might want to add a custom comparator for std::sort

此外,您可能希望为 std::sort