Reputation: 21
I have a template function that performs an index-based selection sort on an indexable object. The IndexedContainer must support operator[]
and size()
, e.g. std::vector
. Container elements must support operator<
and operator=
.
My function must take in any std::vector or array and sort it in ascending order.
Function works but only for vectors since I'm using the size() function. I'm having trouble supporting the operator[] in my function since the size() function does not work for arrays.
#include <iostream>
#include <vector>
template <typename IndexedContainer>
void SelectionSort(IndexedContainer &values) {
// TODO
int temp;
for(unsigned int i = 0; i < values.size(); i++){
for(unsigned int j = i; j > 0; j--){
if(values[j] < values[j-1]){
temp = values[j];
values[j] = values[j-1];
values[j-1] = temp;
}
}
}
}
int main() {
std::vector<char> data = {'a','4','b','2','c','1'};
std::vector<int> data3 = {1,5,6,8,10,2};
//std::vector<std::string> data4 = {"1d23","3v4f","0878"};
char data2[] = "a3b4c1d2";
SelectionSort(data);
SelectionSort(data2);
SelectionSort(data3);
for(auto i: data){
std::cout<<i<<" ";
}
std::cout<<'\n';
std::cout<<data2<<'\n';
for(auto j: data3){
std::cout<<j<<" ";
}
return 0;
}
Upvotes: 0
Views: 74
Reputation: 33924
c++17 introduces std::size
, a free function that encapsulates size for things with the size
member function and arrays. If you don't have c++17, conveniently that link includes an implementation. The crux of which is this specialisation:
template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
return N;
}
Copy that, and use size
free function in your implementation.
Upvotes: 2