【问题标题】:How to use std::max_element on a two dimensional vector如何在二维向量上使用 std::max_element
【发布时间】:2013-06-04 19:06:34
【问题描述】:

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

这就是我所拥有的

#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 >>::operator=(const __gnu_cxx::__normal_iterator > >&)

我尝试了几种解决方案,主要涉及更改我声明 max_it 迭代器的方式。到目前为止没有任何效果,我无法解读错误消息。

【问题讨论】:

  • 有一个错字:应该是myFunction(const ...),而不是myFunction(cont ...)

标签: c++ iterator max std


【解决方案1】:

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

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

【讨论】:

  • 原来如此。我没有在正确的地方寻找答案。谢谢。
  • @vckngs7:很高兴它有帮助。如果这解决了您的问题,请考虑将答案标记为已接受:)
  • 首先要问“你是警察吗?”很重要。 ;)
  • (@vckngs7: 你是警察吗?)
  • 1959 年《街头犯罪法》涵盖了重新征集 ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-26
  • 1970-01-01
  • 1970-01-01
  • 2015-08-09
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多