0

I want to sort my objects according to some criteria (according to how big the items are) My funcSort in multiset slows down calculations and makes the solution does not scale. How can I make it faster? To avoid it I tried to use vector, sort it (should go quicker?) and change it into multiset. My solution however does not work, I am not sure what I do wrong?

Function arguments:

void deliver(const std::set<MyItem::Ptr> items, MyItem::Ptr item)

(Typedef of shared_ptr):

typedef boost::shared_ptr<MyItem> Ptr;

sort function:

  auto funcSort = [item](MyItem::Ptr lhs, MyItem::Ptr rhs){
        return lhs->howFar(item->howBig()) < rhs->howFar(item->howBig());
      };

Original with multiset (SLOW when using funcSort):

  std::multiset<MyItem::Ptr, decltype(funcSort)> sortedItems(funcSort);

  for (MyItem::Ptr item : items){
    sortedItems.insert(item);
  }

My vector attempt (Error message):

  std::vector<MyItem::Ptr> sortedItems;
  for (MyItem::Ptr item : items)
  {
    sortedItems.push_back(item);
  }
  std::sort(sortedItems.begin(), sortedItems.end(), funcSort());
  std::multiset<MyItem::Ptr> ms(sortedItems.begin(), sortedItems.end());

Error message:

   __lambda1
   auto funcSort = [item](MyItem::Ptr lhs, MyItem::Ptr rhs)
 candidate expects 2 arguments, 0 provided
beginh
  • 1,133
  • 3
  • 26
  • 36
  • Can you explain what you are trying to accomplish? – NathanOliver Apr 19 '16 at 13:09
  • and also what "not working" means exactly. – xaxxon Apr 19 '16 at 13:09
  • Why do you need a multiset? Can't you just populate the vector and sort it and now you have a sorted container? – NathanOliver Apr 19 '16 at 13:23
  • `std::sort`, as every function, takes values, not types. You cannot pass result of `decltype` to it. – Revolver_Ocelot Apr 19 '16 at 13:26
  • @NathanOliver if I decide to use vector I have to sort it. But sorting results in error. – beginh Apr 19 '16 at 13:28
  • @beginh Ah. then you need: http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects. or you can just get rid of the `delctype` – NathanOliver Apr 19 '16 at 13:29
  • @NathanOliver, thank you, I was reading already this and changing my sort, but had errors in "lambda" function (updated above). I am not experienced with the c++11 notation that I want to try here out. – beginh Apr 19 '16 at 13:32
  • 1
    You have a typo. `std::sort(sortedItems.begin(), sortedItems.end(), funcSort());` should be `std::sort(sortedItems.begin(), sortedItems.end(), funcSort);` – NathanOliver Apr 19 '16 at 13:43
  • @NathanOliver, the problem was insert() in vector instead of push_back(). Thanks! – beginh Apr 19 '16 at 14:04

1 Answers1

2

You got the sort call wrong. You just want to pass the funcSort, not call it.

Try it like this:

std::sort(sortedItems.begin(), sortedItems.end(), funcSort);
Sorin
  • 11,863
  • 22
  • 26