Re: Is it okay to ask questions about Accelerated C++ exercises here?
On Jun 18, 8:03 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
swivelhead wrote:
I just wanted to check and make sure that it is cool with this group's
rules.
Ask away.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thanks Victor.
This question deals with exercises 10-2 and 10-3.
10-2.
Rewrite the median function from $8.11/140 so that we can call it with
either a vector or a built-in array. The function should allow
containers of any arithmetic type.
10-3.
Write a test program to verify that the median function operates
correctly. Ensure that calling median does not change the order of the
elements in the container.
I will leave out the $8.11/140 example for now, but will post it if
anyone wants. Here is my shot at the median function. (Note, anyone
who has seen the book/examples will see that I added an insertion sort
where the generic sort function would be. I actually made it a
template function also, but the vector container kept passing by value
and not sorting:)
template<typename ReturnType, typename ContainerType>
ReturnType median(ContainerType set, size_t elementTotal) {
if (elementTotal == 0)
throw std::domain_error("median of an empty set");
ReturnType check;
std::cout << "The element total is " << elementTotal << endl;
// perform insertion sort
for(int i = 0; i < elementTotal; i++) {
// grab element value
check = set[i];
// while there is a element to the left that is greater than check
for(int j = i; j > 0 && (set[j - 1] > check); --j) {
// swap the two element values
set[j] = set[j - 1];
set[j - 1] = check;
}
}
// recheck order
std::cout << "rechecking order" << std::endl;
for(size_t index = 0;
index < elementTotal;
++index)
{
std::cout << set[index] << std::endl;
}
// sort<ReturnType, ContainerType>(set, elementTotal);
size_t mid = elementTotal / 2;
return elementTotal % 2 == 0 ? (set[mid] + set[mid - 1]) / 2 :
set[mid];
}
Here's my problem. The vector is passing by value and the array
(pointer) is passing by reference, so even though it finds a median in
both cases, it is altering the order of my array.
This is how I'm calling them from my test program.
vector<int> set1;
...
// set1 is filled
...
cout << "the median is "
<< median<int, vector<int> >(set1, set1.size()) << endl;
const size_t maxint = set1.size();
int *set2 = new int[maxint];
// set2 is filled
cout << "the median is "
<< median<int, int[]>(set2, maxint) << endl;
What are some strategies for accepting both indexed containers by
value?
Thanks.