c++ - 迭代对 vector

标签 c++ vector stl iterator const-iterator

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

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> >*]

谁能帮帮我?

最佳答案

循环中至少有三个错误。

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

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

    cout << it->first;

代替

    cout >> it.first;

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

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

关于c++ - 迭代对 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25606108/

相关文章:

c++ - 如何在C++中将对象的类更改为其当前类的子类?

haskell - 未装箱向量中没有与 unsafeUpdate_ 进行流融合

c++ - std::map 查找不能正常工作

c++ - Visual C++ 2010 映射/设置迭代器不兼容

C++计算 vector 中两个元素之间的差异

c++ - std::string 和 std::basic_string 有什么区别?为什么两者都需要?

c++ - 如何使用curl + ssl而不发生memleak灾难

c++ - C++中的引用和常量混淆

c++ - C++ 预处理器中的 R 和 L 有什么特别之处?

c++ - 指向 Vector 的指针调用的方法无法修改对象