I try to refresh my (very limited) knowledge of C++ and try to implement merge search method:
class Sorter
{
protected:
vector<int> v;
public:
Sorter(){};
Sorter(vector<int> input_vector);
virtual void sort() = 0;
};
Sorter::Sorter(vector<int> input_vector)
{
v.assign(input_vector.begin(), input_vector.end());
}
class MergeSorter : public Sorter
{
public:
MergeSorter():Sorter(){};
MergeSorter(vector<int> input_vector):Sorter(input_vector){};
vector<int> sorted_v;
MergeSorter* left;
MergeSorter* right;
void merge();
void sort();
};
void MergeSorter::sort()
{
if(v.size() <= 1)
return;
int mid = int(v.size() / 2);
left->v.assign(v.begin(), v.begin() + mid);
right->v.assign(v.begin() + mid, v.end() + 1);
left->sort();
right->sort();
left->v.assign(left->sorted_v.begin(), left->sorted_v.end());
right->v.assign(right->sorted_v.begin(), right->sorted_v.end());
merge();
return;
}
...
It does compile, but the program crashes with “Access violation reading location” when I try to assign something to left->v. I feel that I need to actually create an object left (and right) first, but do not know where I do that since it is an object of the same class.
This is correct. Until you create these, they can’t be “used”, since they will be unintialized. You should be able to do the construction and assignment of left and right within your constructor, or initialize them to NULL in the constructor and set them prior to first use if they’re unset at that point.
Note that you will need to take care not to construct these in a way that will cause an infinite loop – creating a new instance within the constructor, which in turn creates a new instance, which in turn….