简体   繁体   English

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

[英]How to use std::max_element on a two dimensional vector

I've looked around for the solution to this problem and was unable to turn up anything. 我到处寻找解决此问题的方法,无法打开任何东西。 I am sure it is a quick fix, hopefully someone can spot my error and show me. 我确信这是一个快速修复,希望有人可以发现我的错误并告诉我。

Here is what I've got 这就是我所拥有的

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

When compiling the above code I get the following error for the line where max_element is called. 编译上面的代码时,在调用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: note: candidates are: __gnu_cxx::__normal_iterator > >& __gnu_cxx::__normal_iterator > >::operator=(const __gnu_cxx::__normal_iterator > >&) /usr/include/c++/4.2.1/bits/stl_iterator.h:637:注意:候选对象为:__gnu_cxx :: __ normal_iterator>>&__gnu_cxx :: __ normal_iterator>> :: operator =(const __gnu_cxx :: __ normal_iterator>> && )

I have tried several solutions, mostly involving changing how I declare the max_it iterator. 我尝试了几种解决方案,主要涉及更改我声明max_it迭代器的方式。 Nothing has worked so far and I am unable to decipher the error message. 到目前为止没有任何工作,我无法破译错误消息。

Your iterator should be a constant iterator, since you are invoking begin() and end() through a reference to const : 您的迭代器应该是一个常量迭代器,因为您是通过引用const来调用begin()end()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM