I'd like to run this simple code:
#include <cstdlib> //std :: rand ()
#include <vector> //std::vector<>
#include <list> //std::list<>
#include <iostream> //std::ostream_iterator
#include <iterator> //std:: cout std::ostream_iterator
#include <algorithm> //std::reverse, std::generate
#include <map>
#include "ColorRGB.hpp"
#include "point2d.hpp"
#include "circle.hpp"
#include <cmath>
int main(){
std::list<Circle>lk;
Point2d a(7.5,3.2);
Point2d b(6.5,2.2);
Point2d c(5.5,1.2);
ColorRGB d(0, 0, 0);
ColorRGB e(0, 1, 1);
ColorRGB f(1, 1, 0);
Circle c1(a, 2, d);
Circle c2(b, 1, e);
Circle c3(c, 0.4, f);
lk.push_back(c1);
lk.push_back(c2);
lk.push_back(c3);
sort(lk.begin(), lk.end(), [] (Circle const& lhs,Circle const& rhs)
->bool{return(lhs.getrad() <= rhs.getrad())};
return 0;
}
but get the compile message:
Juliuss-MacBook-Pro-2:uebung4 JONG$ g++ -o 4_1 4_1.cpp
4_1.cpp:42:30: error: expected expression
sort(lk.begin(), lk.end(), [] (Circle const& lhs,Circle const& r...
^
1 error generated.
You can not sort a list
using std::sort
because std::sort
requires a random access iterator and list
has a bidirectional iterator only.
Use a vector
instead. Alternatively, if you insist on using list, there is a member function called list.sort()
. It can accept a custom comparator as well.
Related question / answers here
Also, use an SSCCE in the question. That means getting rid of/providing the code of custom classes as much as possible.
You also had errors in the braces. Here is a code that is self-contained and also compiles. It show the usage of both std::sort
with vector
and the list::sort
function:
#include <list>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
class Circle
{
int r;
public:
Circle(int r) : r(r) {}
int getrad() const { return r; }
};
int main(){
std::vector<Circle> vk;
std::list<Circle> lk;
Circle c1(2);
Circle c2(1);
Circle c3(3);
vk.push_back(c1);
vk.push_back(c2);
vk.push_back(c3);
lk.push_back(c1);
lk.push_back(c2);
lk.push_back(c3);
std::sort(vk.begin(), vk.end(),
[] (const Circle& lhs, const Circle& rhs) -> bool {
return lhs.getrad() < rhs.getrad();
});
lk.sort(
[] (const Circle& lhs, const Circle& rhs) -> bool {
return lhs.getrad() < rhs.getrad();
});
return 0;
}
Still, I recommend vector
.
After the OPs update:
As pointed out by @nwp, use a C++11 compiler if you use lambas:
g++ -std=c++11 -Wall -Wextra filename.cpp
As pointed out by @WhozCraig , the comparator also needed a fix.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.