473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Is it okay to ask questions about Accelerated C++ exercises here?

I just wanted to check and make sure that it is cool with this group's
rules.

Thanks.
Jun 27 '08 #1
8 1079
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
Jun 27 '08 #2
swivelhead <je*****@gmail.comwrote:

Wow! You did a lot of research and this is a much better second draft.
Now for the final draft... :-)

First, look up 'distance' in your reference so your algorithm will work
with lists as well as vectors and deques.
// median.h
#ifndef GUARD_MEDIAN_H
#define GUARD_MEDIAN_H

#include <algorithm>
#include <cstring>
#include <iostream>
#include <iterator>
#include <stdexcept>
#include <vector>
>
template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
median(InputIterator first, InputIterator last)
{
typedef typename
std::iterator_traits<InputIterator>::value_type ReturnType;
typedef typename
std::iterator_traits<InputIterator>::difference_ty pe DiffType;

DiffType elementTotal = last - first;

if (elementTotal == 0)
throw std::domain_error("median of an empty set");
Another way to do the above... if (first == last)... You don't need
elementTotal.
// built the temporary container
std::vector<ReturnTypetempSet;
>
// fill in the temporary container
copy(first, last, back_inserter(tempSet));
Instead of making the vector, then copying it, then sorting it. Look
into using partial_sort_copy. Only copy the half of the input that you
need.

At this point, tempSet.size() == elementTotal... You don't need both
variables, they are the same. So remove elementTotal.
DiffType halfElementTotal = elementTotal / 2;
typename std::vector<ReturnType>::iterator throughMedianIter =
tempSet.begin() + halfElementTotal + 1;

// sort the temporary container through (one passed) the midpoint
std::partial_sort(
tempSet.begin(),
throughMedianIter,
tempSet.end());

bool hasEvenElements = elementTotal % 2 == 0;
DiffType midPoint = halfElementTotal;
midPoint == halfElementTotal... You don't need both variables, they are
the same.
ReturnType median =
hasEvenElements ?
(tempSet[midPoint] + tempSet[midPoint - 1]) / 2 :
tempSet[midPoint];

return median;
}

#endif GUARD_MEDIAN_H
// end of median.h
Jun 27 '08 #3
Thanks again Daniel and Michael. This has been an interesting
exercise.

I did a check for first == last and left it at the top in my latest
draft. Does that disqualify it from using lists?

Also, does midPoint need to be of the type
std::iterator_traits<vector<ReturnType>::iterator> ::difference_type?

Here's the results:

template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
median(InputIterator first, InputIterator last)
{
if (first == last)
throw std::domain_error("median of an empty set");

// built the temporary container big enough to do a partial sort of
one more
// of one more than half the size of the input container (odd or
even) to
// accomadate the median
typedef typename
std::iterator_traits<InputIterator>::difference_ty pe DiffType;

DiffType origSize = std::distance(first, last);

typedef typename
std::iterator_traits<InputIterator>::value_type ReturnType;

vector<ReturnTypetempSet((origSize / 2) + 1);

// fill in the temporary container while sorting
std::partial_sort_copy(
first,
last,
tempSet.begin(),
tempSet.end());

DiffType midPoint = tempSet.size() - 1;

ReturnType median =
origSize % 2 == 0 ?
(tempSet[midPoint] + tempSet[midPoint - 1]) / 2 :
tempSet[midPoint];

return median;
}
Jun 27 '08 #4
swivelhead <je*****@gmail.comwrote:
Thanks again Daniel and Michael. This has been an interesting
exercise.

I did a check for first == last and left it at the top in my latest
draft. Does that disqualify it from using lists?

Also, does midPoint need to be of the type
std::iterator_traits<vector<ReturnType>::iterator> ::difference_type?
No, it should be the same type as vector<ReturnType>::size()'s return
type. Which for all vectors is vector<T>::size_type. (Which is
convertible to size_t hence Michael's response is acceptable.)
Here's the results:
After applying Michael's final changes, compare the end result with your
first draft and be amazed... It calls to mind Blaise Pascal's quote:
"...my letters were not wont... to be so prolix... Want of time must
plead my excuse..."

It takes time to make code succinct.

Personally, I would have eliminated 'median', 'midPoint' as well. The
information in those variables is redundant.
template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
median(InputIterator first, InputIterator last)
{
if (first == last)
throw std::domain_error("median of an empty set");

// built the temporary container big enough to do a partial sort of
one more
// of one more than half the size of the input container (odd or
even) to
// accomadate the median
typedef typename
std::iterator_traits<InputIterator>::difference_ty pe DiffType;

DiffType origSize = std::distance(first, last);

typedef typename
std::iterator_traits<InputIterator>::value_type ReturnType;

vector<ReturnTypetempSet((origSize / 2) + 1);

// fill in the temporary container while sorting
std::partial_sort_copy(
first,
last,
tempSet.begin(),
tempSet.end());

DiffType midPoint = tempSet.size() - 1;

ReturnType median =
origSize % 2 == 0 ?
(tempSet[midPoint] + tempSet[midPoint - 1]) / 2 :
tempSet[midPoint];

return median;
}
Jun 27 '08 #5
>
After applying Michael's final changes, compare the end result with your
first draft and be amazed... It calls to mind Blaise Pascal's quote:
"...my letters were not wont... to be so prolix... Want of time must
plead my excuse..."

It takes time to make code succinct.

Personally, I would have eliminated 'median', 'midPoint' as well. The
information in those variables is redundant.
The differences are crystal clear. My next step is two do some tests
with other container types and numeric types.

Thanks for the incredible information!

BTW: I kept the median/midPoint variables just for readability's sake.
I'm a verbose programmer and like things laid out and obvious because,
frankly, I don't remember much about the code I wrote last month.
Also, I don't like returning from an operator statement.

Here's my final, final, (final?) draft:

template<typename ForwardIterator>
typename std::iterator_traits<ForwardIterator>::value_type
median(ForwardIterator first, ForwardIterator last)
{
if (first == last)
throw std::domain_error("median of an empty set");

// built the temporary container big enough to do a partial sort of
one more
// of one more than half the size of the input container (odd or
even) to
// accomadate the median
typedef typename
std::iterator_traits<ForwardIterator>::difference_ type DiffType;

DiffType origSize = std::distance(first, last);

typedef typename
std::iterator_traits<ForwardIterator>::value_type ReturnType;

vector<ReturnTypetempSet((origSize + 2) / 2);

// fill in the temporary container while sorting
std::partial_sort_copy(
first,
last,
tempSet.begin(),
tempSet.end());

vector<ReturnType>::size_type midPoint = tempSet.size() - 1;

ReturnType median =
origSize % 2 == 0 ?
(tempSet[midPoint] + tempSet[midPoint - 1]) / 2 :
tempSet[midPoint];

return median;
}
Jul 1 '08 #6
Here's the results:
[snip]
* vector<ReturnTypetempSet((origSize / 2) + 1);

Use:
vector<ReturnTypetempSet( (origSize+1) / 2 );
Um.. See Below
>
It computes the exact value and avoids the UB you would have hereafter
in the case of the border effect (origSize==1).
* // fill in the temporary container while sorting
* std::partial_sort_copy(
* * * first,
* * * last,
* * * tempSet.begin(),
* * * tempSet.end());
* DiffType midPoint = tempSet.size() - 1;

If using (origSize / 2) + 1 with origSize==1, then
* * tempSet.size()=2 =midPoint=1;
But tempSet[midpoint] is not set.
How? (1/2) + 1 will equal 1, so tempSet.size() will equal 1.
The problem is when origSize is even, say '2'; then your tempSet size
will only end up being '1' big. The original poster had it right; I
think you've introduced a bug.

Joe Cook
Jul 1 '08 #7
How? * (1/2) + 1 will equal 1, so tempSet.size() will equal 1.
The problem is when origSize is even, say '2'; then your tempSet size
will only end up being '1' big. * The original poster had it right; I
think you've introduced a bug.

Indeed I did.
I tested it out and adding 2 instead of 1, as in:

vector<ReturnTypetempSet((origSize + 2) / 2);

seems to work, like my original statement:

vector<ReturnTypetempSet((origSize / 2) + 1);

Here's some quick examples of how they match:
((origSize / 2) + 1)
origSize tempSet.size()
1 1
2 2
3 2
4 3
5 3
6 4
11 6

((origSize + 2) / 2)
origSize tempSet.size()
1 1
2 2
3 2
4 3
5 3
6 4
11 6

I originally thought it would affect a different calculation for
median, therefore, I changed it. However, it was intesting finding
out that both calculations were equivalent because of the "division of
an odd int" characteristic in C++.
Jul 2 '08 #8
I originally thought it would affect a different calculation for
median, therefore, I changed it. *However, it was intesting finding
out that both calculations were equivalent because of the "division of
an odd int" characteristic in C++.
Wait a minute, they would be equivalent in normal division too. I
should have recognized that. I think I need some more sleep!
Jul 2 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
by: Martin | last post by:
I am reading through Koenig and Moo's "Accelerated C++" and attempting the exercises. Are there any sample solutions somewhere? It's all very well me doing a solution, which seems to work, but for...
35
by: Markus Dreyer | last post by:
I suggested our Librarian for the University Library to buy Accelerated C++. Practical Programming by Example. by Andrew Koenig and Barbara E. Moo http://www.acceleratedcpp.com/ but she...
3
by: Frankie Montenegro | last post by:
Hi everyone, I must say that, even though I think that Accelerated C++ by Koenig and Moo is an awesome text, the wording of exercises is very poor. I spend half the time just trying to figure...
14
by: Pete | last post by:
Is anyone familiar with this book? Exercise 6-1 of Accelerated C++ asks us to reimplement the frame() and hcat() operations using iterators. I've posted my answers below, but I'm wondering if...
1
by: utab | last post by:
Hi there, I have been reading Accelerated C++ by Andrew Koenig which is an excellent way of learning C++ from even the first pages by using the standard library. One drawback is that no...
8
by: utab | last post by:
Dear all, in a container example, this question is asked in exercises in Accelerated C++ page 154, 8.8? why dont we use (begin+end)/2 instead of begin + (end - begin) / 2 is that someting related...
1
by: blangela | last post by:
I am currently teaching 2 part-time (one evening per week) C++ courses using the Deitel & Deitel "C++ How To Program" text. Each course is 13 weeks in length, including time for labs and exams. ...
4
by: Jess | last post by:
Hello, I tried several books to find out the details of object initialization. Unfortunately, I'm still confused by two specific concepts, namely default-initialization and...
3
by: duli | last post by:
Hi: I am a newbie learning C++ by going through "Accelerated C++" by Koenig and Moo. I am a little overwhelmed by the complexity and breadth of C++ and don't know how I can learn it...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.