Insertion Sort Not Working For Classes?
Feb 28, 2016 at 8:30am UTC
So, I've created a class shape, which has the height, width and length of a 3D shape. Then, I create a function, that sorts it by height, but it doesn't work. When I tried it with bubble sort it did. Am I doing anything wrong in the function?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include<iostream>
#include<vector>
using namespace std;
typedef long double ld;
class shape{
public :
ld length;
ld width;
ld height;
shape(){
length = 0;
width = 0;
height = 0;
}
public :
void make_shape(ld a, ld b, ld c){
length = a;
width = b;
height = c;
}
ld volume(){
ld answer = length * width * height;
return answer;
}
};
void sort_height(vector<shape>cube_sort, int length){
for (int i=0; i<length-1; i++){
for (int j=i; j>0; j--){
if (cube_sort[j].height < cube_sort[j-1].height){
swap(cube_sort[j], cube_sort[j-1]);
}
}
}
}
int main(){
vector <shape> cubes(1000, shape());
ld a, b, c;
int place = 0;
while (cin>>a>>b>>c){
cubes[place].make_shape(a, b, c);
place++;
}
sort_height(cubes, cubes.size());
for (int i=0; i<place; i++){
cout<<cubes[i].height<<"\n" ;
}
}
Last edited on Feb 28, 2016 at 8:30am UTC
Feb 28, 2016 at 8:58am UTC
Probably some logic error in your function. Why don't you use std::sort and create predicate for sorting like
1 2 3 4 5 6 7 8 9 10 11
struct pred
{
bool operator ()(const shape& s1, const shape& s2) { return s1.height < s2.height; }
};
//and than in your main()
std::sort(cubes.begin(), cubes.end(), pred{});
//or using lambda
using height_sort = [](const shape& s1, const shape& s2){return s1.height < s2.height;}
std::sort(cubes.begin(), cubes.end(), height_sort);
Of course if this is an exercise (making that sort funtion yourself) than you just have to find that logic error
Last edited on Feb 28, 2016 at 9:00am UTC
Feb 28, 2016 at 9:15am UTC
I wanted just to sort it. I didn't know that you can customize the sort() function. Thanks! I'll look it up to learn more.
Topic archived. No new replies allowed.