在g ++中编译时出现max_element stl错误

时间:2015-09-03 08:48:37

标签: c++ stl

这是程序,我正在尝试使用stl向量实现priority_queue: 有一个编译时错误,我在最后粘贴了复制。感谢帮助。 Top()函数实现中存在错误。

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

/*
APIs to be supported:
1. Top()
2. Pop()
3. Push()
DS:
vector
Algo:
*/

template<typename T>
class MyOwnPQ
{
    public:
    vector<T> vContainer;

    bool cmp_fync(T a, T b)
    {
        return a < b;
    }

    void Top() const
    {
        typename vector<T>::iterator pos; //Very important does not compile without the typename.
        pos = max_element(vContainer.begin(), vContainer.end());
        //return *pos;
    }

    void Push(const T& element)
    {
        vContainer.push_back(element);
    }

};

int main()
{
    MyOwnPQ<int> m_MyOwnPQ;
    m_MyOwnPQ.Push(1);
    m_MyOwnPQ.Push(2);
    m_MyOwnPQ.Push(3);

    m_MyOwnPQ.Top();

}

错误是:

E:\c++>g++ MyOwnPQ.cpp
MyOwnPQ.cpp: In member function 'void MyOwnPQ<T>::Top() const [with T = int]':
MyOwnPQ.cpp:49:   instantiated from here
MyOwnPQ.cpp:31: error: no match for 'operator=' in 'pos = std::max_element [with _FIter = __gnu_cxx::__normal_iterator<const int*, std::vector<int, std::allocator<int> > >](((const MyOwnPQ<int>*)this)
->MyOwnPQ<int>::vContainer.std::vector<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>](), ((const MyOwnPQ<int>*)this)->MyOwnPQ<int>::vContainer.std::vector<_Tp, _Alloc>::end [with _
Tp = int, _Alloc = std::allocator<int>]())'
c:\dwimperl\c\bin\../lib/gcc/i686-w64-mingw32/4.4.7/../../../../include/c++/4.4.7/bits/stl_iterator.h:691: note: candidates are: __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int>
 > >& __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >::operator=(const __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >&)

非常感谢帮助:)。

3 个答案:

答案 0 :(得分:2)

您正尝试在const上下文中分配一个普通的迭代器(因为您声明Top可以与const对象一起使用)。将迭代器更改为const_iterator

typename vector<T>::const_iterator pos;

答案 1 :(得分:0)

你的函数Top()被声明为const,它使用成员变量vContainer。 因此,您无法使用&#34;标准&#34;迭代器,但是const迭代器:

typename vector<T>::const_iterator pos

答案 2 :(得分:0)

似乎你需要价值但是需要

app:cardUseCompatPadding="true"

否则使用void Top() const { T value = *max_element(vContainer.begin(), vContainer.end()); . . . }

auto