为什么在* max_element上使用cout(v.begin(),v.end(),c);抛出这个巨大的错误?

时间:2014-01-22 05:07:40

标签: c++ stl

STL.cpp: In function ‘int main()’:
STL.cpp:56:86: error: no match for ‘operator<<’ in ‘std::operator<< <std::char_traits<char> >((* &std::cout),((const char*)"The Point with the largest Y value is ")) << std::max_element<__gnu_cxx::__normal_iterator<Point*, std::vector<Point> >, Compare_Y>(v.std::vector<_Tp, _Alloc>::begin<Point, std::allocator<Point> >(), v.std::vector<_Tp, _Alloc>::end<Point, std::allocator<Point> >(), (c, Compare_Y())).__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<Point*, std::vector<Point> >()’
STL.cpp:56:86: note: candidates are:
In file included from /usr/include/c++/4.7/iostream:40:0,
             from STL.cpp:2:

...等...

/usr/include/c++/4.7/ostream:546:5: note: template<class _Traits> std::basic_ostream<char, _Traits>& std::operator<<(std::basic_ostream<char, _Traits>&, const unsigned char*)
/usr/include/c++/4.7/ostream:546:5: note:   template argument deduction/substitution failed:
STL.cpp:56:86: note:   cannot convert ‘std::max_element<__gnu_cxx::__normal_iterator<Point*, std::vector<Point> >, Compare_Y>(v.std::vector<_Tp, _Alloc>::begin<Point, std::allocator<Point> >(), v.std::vector<_Tp, _Alloc>::end<Point, std::allocator<Point> >(), (c, Compare_Y())).__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator*<Point*, std::vector<Point> >()’ (type ‘Point’) to type ‘const unsigned char*’

大多数有类似错误的人似乎都错误地输入某种某种std ::'某种东西',但据我所知,情况并非如此。我现在精神萎靡,有点糊涂。我只复制了由于此错误而给出的详细文本块的1/4。我的代码如下。我知道这是我第一次使用STL算法,但一切似乎都是有序的。我想这就是我们学习的方式。

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

using namespace std;

class Point{
        int x,y;//Integer coordinates for simplicity
public:
        Point();
        Point(int, int);

        double get_Y() const {return y;}

        void Print();
};

Point::Point(){//Initialize blank Points to blank values (zero)
        x = 0;
        y = 0;
}

Point::Point(int a, int b){
        x = a;
        y = b;
}

void Point::Print(){
        cout<< "Point: (" << x << "," << y << ")" << '\t';

}
//comparison function for comparing Point class objects
struct Compare_Y{
        bool operator()(const Point& p1, const Point& p2)
                { return p1.get_Y() > p2.get_Y(); }
};

int main(){

        //Store 10 Points in any container, initialize, and print each Point
        vector<Point> v;

        for(int i = 0; i < 10; ++i){
        v.push_back(Point(i*5,i*10));
        }

        for(int i = 0; i < 10; ++i){
        v[i].Print();
        }

        //Write function to find Point with maximum y coordinate by any STL Algorithm (See C++ site w/ them)
        //Return the point with the max y coord. Return the x AND y here.

        Compare_Y c;
        cout << "The Point with the largest Y value is " << *max_element(v.begin(),v.end(),c);

return 0;

}

不,这不是功课。这种做法不适用于等级,我们被告知我们必须使用至少一个STL算法,这就是我选择* max_element的原因,因为我们的TA在我做笔记的例子中使用了它。

0 个答案:

没有答案