Tuesday, July 28, 2009

Pointers in c++ - i want only the pointers sorted?

char *cities[ ]={"New York","Washington","Durham","Cincinati"}...


char **c;


c = cities; // i want to have the pointers sorted but the cities must remain in exact place.

Pointers in c++ - i want only the pointers sorted?
Assuming you want them sorted into an order based on what they point to. Then create a parallel array in which they are placed in sorted order. Changing there order there doesn't change the location they point to or the ordering in the original array.





In the above assigning


c = cities


makes c and alias for cities. What you what to do is make a deep copy as below.








char* cities[] = {.....};


char** toSort = calloc(sizeof(cities)/sizeof(*cities), sizeof(char*));





for (int i = 0; i %26lt; sizeof(cities)/sizeof(*cities); ++i)


toSort[i] = cities[i];





//sort toSort;





cities[] is left in it's original order


the cities in toSort are ordered


No comments:

Post a Comment