如何在二维向量上使用std::max_element



我四处寻找这个问题的解决方案,但没有找到任何解决方案。我相信这是一个快速修复,希望有人能发现我的错误并告诉我。

这是我得到的

#include<algorithm>
#include<vector>
void myFunction ( cont std::vector<std::vector<int> > &counts){
    std::vector<int>::iterator max_it;
    int index;
    for ( int i = 0 ; i < counts.size() ; i ++ ){
        max_it = std::max_element(counts[i].begin(), counts[i].end());
        index = std::distance(counts[i].begin(),max_it);
    }
}

在编译上面的代码时,在调用max_element的那一行,我得到了以下错误:

error: no match for ‘operator=’ in ‘it = std::max_element [with _ForwardIterator = __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >](((const std::vector<int, std::allocator<int> >*)((const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >*)counts)->std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::vector<int, std::allocator<int> >, _Alloc = std::allocator<std::vector<int, std::allocator<int> > >](((long unsigned int)i)))->std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>](), ((const std::vector<int, std::allocator<int> >*)((const std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >*)counts)->std::vector<_Tp, _Alloc>::operator[] [with _Tp = std::vector<int, std::allocator<int> >, _Alloc = std::allocator<std::vector<int, std::allocator<int> > >](((long unsigned int)i)))->std::vector<_Tp, _Alloc>::end [with _Tp = int, _Alloc = std::allocator<int>]())’

/usr/include/c++/4.2.1/bits/stl_iterator.h:637:注意:候选对象为:__gnu_cxx::__normal_iterator>>&__gnu_cxx: __normal_iterator>>::操作符= (const __gnu_cxx: __normal_iterator>>,)

我尝试了几种解决方案,主要涉及改变max_it迭代器的声明方式。到目前为止没有任何工作,我无法破译错误信息。

你的迭代器应该是常量迭代器,因为你通过对const的引用来调用begin()end():

std::vector<int>::const_iterator max_it;
//                ^^^^^^

最新更新