-2

I'm working on a basic DFS algorithm for my oriented graph in c++.

What i got, is a class Vertex which have a char value and a list of adjacence.

Given that, i'm trying to sort a list of object (in my case vertex, but let's say something else) by its value.

My class is something like that:

class Foo {
private:
    char x;
    list<Foo*> listOfChildrenObject;
};

let's say we got 5 Foo's object.

A,B,C,D,E

now, A is the father of every object in my program.

let's say i've inserted them in this way:

A (the father), D, C, B, E

and then, i want to print them in order:

A,B,C,D,E

and for that, i want to use listOfChildrenObject.sort() to do that.

there's a way to sort my list of object by the char value?

Asynchronousx
  • 101
  • 1
  • 1
  • 8
  • Provide a `operator<` for `Foo` – Passer By Nov 27 '17 at 19:10
  • @PasserBy It's a list of `Foo*`. – n. m. could be an AI Nov 27 '17 at 19:12
  • @PasserBy, that won't be enough. `listOfChldrenObject` is a list of pointers. – R Sahu Nov 27 '17 at 19:13
  • 1
    It's a little more complicated with pointers, but you just need a predicate that dereferences them. http://en.cppreference.com/w/cpp/container/list/sort – Retired Ninja Nov 27 '17 at 19:13
  • 8
    Whatever container you use is absolutely fine, just make sure it's not a linked list. Thank me later. – n. m. could be an AI Nov 27 '17 at 19:14
  • My mistake. What @RetiredNinja said. `listOfChildrenObject.sort([](Foo* x, Foo* y){ return (*x) < (*y); })`, provided the `operator<` is already there. – Passer By Nov 27 '17 at 19:15
  • 1
    Possible duplicate of [Sort a list of pointers](https://stackoverflow.com/questions/2554405/sort-a-list-of-pointers) – Retired Ninja Nov 27 '17 at 19:16
  • Please [do not use _raw pointers_](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr) in c++ code. – user0042 Nov 27 '17 at 19:16
  • @n.m. The container of last resort. :) – Retired Ninja Nov 27 '17 at 19:17
  • @user0042: There's nothing wrong with using raw pointers. The answers in the link you provide don't even support your statement. They are almost entirely concerned with ownership of dynamically allocated resources, and that is not the only purpose of pointers. – Benjamin Lindley Nov 27 '17 at 19:34
  • @BenjaminLindley I love to have my raw pointer for breakfast along a reasonable usage of `T::get()` or `&T::data()` ;-) ... (that's like _milk on top of the cereals_) – user0042 Nov 27 '17 at 19:37

1 Answers1

0

Ok, i think i got it.

sorry for the dumb and repeated question, i resolved adding a lambda function to my sort, and changing the list to a vector (i realized that i had no reason to use a list)

in this way:

std::sort(v.begin(), v.end(), [](Foo* a, Foo* b) {return a->getValue() < b->getValue(); });
Asynchronousx
  • 101
  • 1
  • 1
  • 8