I'm very new to C++ (2 weeks at present) and could really do with some help. I'm using the following
1 2 3 4 5 6 7 8
template <class arr, class elmt> void ins_b_b4_a(arr v, elmt sample, int* n, int b, int a)
{ // Inserts elmt b before elmt a in an array. NOTE: Ensure that b > a when using.
elmt tmp = *(v+b);
memmove(&(*(v+a+1)), &(*(v+a)), sizeof(sample) * (b-a)); // Note that memmove takes ptrs. simply v+a would do,
// but this is more explicit.
*(v+a) = tmp; // Note also, memcpy won't work as blocks of memory overlap
if (n) ins_b_b4_a(&n[0], n[0], 0, b, a);
}
as part of an insertion sort routine I'm writing. The function works for integers, doubles, etc, but not for strings. Why is this please? And what can I do about it? I get a value of 4 for sizeof(strarr[i]), which presumably refers to the pointer to the string table (?), in which case I thought I could use memmove to shift the pointers or something like that?
void ins_b_b4_a(string* v, string sample, int* n, int b, int a)
{ // Inserts elmt b before elmt a in an array. NOTE: Ensure that b > a when using.
string tmp = *(v+b);
for (int i=b; i>a; i--) *(v+i) = *(v+i-1);
*(v+a) = tmp; // Note also, memcpy won't work as blocks of memory overlap
if (n) ins_b_b4_a(&n[0], n[0], 0, b, a);
}
but it seems like there should be a better way, right?
You shouldn't do it like this.
If you want to write a sort function that will work for any type, you need to give the user the ability to provide their own comparison function, and their own swap function.
It would look something like this:
1 2
template <typename T>
void sort(T *array,size_t n,int (*compare)(const T &,const T &),void(*swap)(T &,T &));
EDIT: I just noticed that that's actually a support function, but the concept still applies.
Right. Good idea about the compare function. I can see how that would be helpful. I have a swap function as you describe; I was just seeing if I could get an insertion type function down too.