Overloading Vector Functions Without Overloading

The title is almost illogical, but I was trying to be clever.

Anyway, this is more for functions requiring vectors than anything else. I'm wondering if there's any way to write a function that will take in any vector type (int, string, foo, etc.) and still work properly. I know C++ is a strong-typed language, but let's delve into my nonsensical mind for a second. Say we have this function:

1
2
3
4
5
6
7
8
9
10
11
vector<string> shuffle(vector<string> vct) {
  int size = vct.size();

  // shuffle the vector
  // by swapping elements
  for (int i = 0; i < size; i++) {
    swap(vct[i], vct[rand(0, size-1)]);
  }

  return vct;
}


Let's say I want to use this same function, but I don't want to have to copy & paste the same code just different variable types; it just looks messy.

Is there any way to do this, or am I wishing for pigs to fly?

(rand() is a custom function that randomly selects a random integer value between two numbers. Ignore it.)
Templates are for that. See http://www.cplusplus.com/doc/tutorial/templates/

In this case the code would be
1
2
3
4
5
template<typename T>
vector<T> shuffle( vector<T> vct) {
   // your function body. everywhere you'd write 'string' or 'int', write T.
   // though your original code has none of those..
}
The most general form would be

1
2
3
4
5
6
template< typename T, typename Alloc >
std::vector<T, Alloc>& shuffle( std::vector<T, Alloc>& v )
{
    // do stuff
    return v;
}


since vector has two template parameters, not one. Also, I'm assuming that you don't want to kill performance by passing a copy of the vector into the function, so I made it a reference here.

Also, one other point is that your algorithm is essentially already std::random_shuffle().
Topic archived. No new replies allowed.