Re Order array or use lookup table?

May 23, 2020 at 12:25pm
I have an array of objects and I want to either call them in a specific order or re order the list entirely. Also is there a way to sort based on an objects variable?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <algorithm>
#include <array>

class ClassA
{
public:
	int orderNum;
	ClassA(int a)
	{
		orderNum = a;
	}
};


int main()
{
	ClassA myClassA[] = { ClassA(45),ClassA(15), ClassA(12), ClassA(5) };
	std::sort(myClassA[begin], myClassA [end], this->orderNum)
}
May 23, 2020 at 12:37pm
Check it out

https://en.cppreference.com/w/cpp/algorithm/sort

Try

1
2
3
4

std::sort(std::begin(myClass),std::end(myClass), //comparison function  here);

Last edited on May 23, 2020 at 12:38pm
May 23, 2020 at 1:27pm
You would need to define an operator< for your class. Then, you can simply do:
1
2
3

std::sort(std::begin(myClassA), std::end(myClassA));


Without a predicate.
May 23, 2020 at 5:12pm
if the objects are large, fat things you can make an array of pointers and sort that by the given criteria. that lets you have just 1 real copy of the objects. Your example is too small to fool with this idea, but maybe you have a bigger class in your real code where this would make sense. You can also use sort-keys to reduce the trouble:
1
2
3
4
5
6
class magic
{
    string sortkey;
    string lastname;
    string zipcode;
}


say you made sortkey like this: zipcode+'|'+lastname;
and sorted that array off sortkey.
it would be the same as if you sorted it by zipcode and then by lastname, but you only have to sort it one time.
Topic archived. No new replies allowed.