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;
}
Aucun commentaire:
Enregistrer un commentaire