templates - sorting a list containing circles c++ -


i'd run 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 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 list using std::sort because std::sort requires random access iterator , list has bidirectional iterator only.

use vector instead. alternatively, if insist on using list, there member function called list.sort(). can accept custom comparator well.

related question / answers here


also, use sscce in question. means getting rid of/providing code of custom classes as possible.


you had errors in braces. here code self-contained , compiles. show usage of both std::sort vector , 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, recommend vector.


after ops update:

as pointed out @nwp, use c++11 compiler if use lambas:

g++ -std=c++11 -wall -wextra filename.cpp 

as pointed out @whozcraig , comparator needed fix.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -