Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Acclerated C++ : Can I write a program that sorts either a list or a vector using the same command?

Tags:

c++

I realize that the std::sort function requires use of random access iterators, and lists have bidirectional iterators. There is a question regarding this at :

Sort list using STL sort function

I am working to answer question 5-4 in the Accelerated C++ book for home study purposes.

5-4. Look again at the driver functions you wrote in the previous exercise. Note that it is possible to write a driver that only differs in the declaration of the type for the data structure that holds the input file. If your vector and list test drivers differ in any other way, rewrite them so that they differ only in this declaration.

Besides this textbook question, this would be useful if I used templates instead of typedef to define a container type.

(Be aware this could happen to you by the pronoun censors: https://www.theregister.co.uk/2019/10/08/stack_overflow_apology/)

like image 289
yellowjacket05 Avatar asked Dec 08 '22 08:12

yellowjacket05


1 Answers

...sorts either a list or a vector using the same command?

The easiest way is to use overloading:

template <typename T>
inline void sort(std::vector<T>& x) { std::sort(x.begin(), x.end()); }

template <typename T>
inline void sort(std::list<T>& x) { x.sort(); }

UPDATE

You imply that your text hasn't introduced templates yet, so here's a template-free alternative. The question says "only differs in the declaration of the type for the data structure that holds the input file" and we're talking about vector and list, so there must be something like:

std::vector<std::string> input;

Maybe the type isn't std::string - you might have your own data type - but whatever it is, Standard containers - including vector and list - have a typedef so that the contained type can be refered to a la decltype<input>::value_type. This means you can write more restrictive versions of the templates that only work for vectors and lists with that specific value type:

inline void sort(std::vector<decltype<input>::value_type>& x) { std::sort(x.begin(), x.end()); }

inline void sort(std::list<decltype<input>::value_type>& x) { x.sort(); }

Of course, if you want to just hardcode std::string or whatever the value type currently is that'll work fine too - only issue from a maintenance perspective is that you'll need to change this code if you change the value type later.

inline void sort(std::vector<std::string>& x) { std::sort(x.begin(), x.end()); }

inline void sort(std::list<std::string>& x) { x.sort(); }
like image 122
Tony Delroy Avatar answered Dec 22 '22 00:12

Tony Delroy