I am writing a class to test the efficient of different sorting algorithms (for a college course), and of the algorithms I'm supposed to test is the STL sort. To measure efficiency, we've defined a class Integer that holds and integer value, and also allows us to increment a global variable each time it is compared or assigned. I then have a driver class which tests the std::sort call on multiple vectors of integers. I have overloaded the '<' operator in my Integer class, and it conforms to strict weak ordering (at least I'm pretty sure it does). Every time I call sort, however, I get a segmentation fault. I really can't figure out why this is happening, any help would be greatly appreciated. Thanks!
Integer.cpp
#include "Integer.h"
int Integer_count;
//Default Constructor
Integer::Integer() {
val = 0;
}
//Specified Constructor
Integer::Integer(int x) {
val = x;
}
//Copy-Constructor
Integer::Integer(const Integer &cp) {
Integer_count++;
val = cp.val;
}
//Return the Integer's value
int Integer::value() {
return val;
}
//Less-than (<) operator overload
bool Integer::operator < (const Integer& obj) const {
Integer_count++;
return (val < obj.val);
}
//Assignment (=) operator overload
void Integer::operator = (const Integer& obj) {
Integer_count++;
val=obj.val;
}
driver.cpp
#include <iostream>
#include <cstdlib>
#include <vector>
#include "Integer.h"
#include "Sorter.cpp"
srand (time(NULL)); //Seed the random number generator
std::vector<Integer> one;
std::vector<Integer> two;
std::vector<Integer> three;
std::vector<Integer> four;
std::vector<Integer> five;
for(int i=0; i<10000; i++){
one[i] = Integer(i);
two[i] = Integer(10000-i);
three[i] = Integer(rand() % (10000+1));
four[i] = Integer(rand() % (10000+1));
five[i] = Integer(rand() % (10000+1));
}
//Sort function called from the STL
//Sorted Array
std::sort(one.begin(), one.end());
std::cout << "STL for Sorted Array: " << Integer_count << std::endl;
Basically, I think the std::sort function is not using the overloaded operator from my Integer class, which is messing up the stack. I don't know for certain is this is the error however, and can't seem to resolve it.
Aucun commentaire:
Enregistrer un commentaire