Function that calculates the arithmetic mean using vectors?

J

John Harrison

Protoman said:
How do I access the induvidual elements of a vector if I have no idea
how many there are?

You can use the size() method to find out how big a vector is.

john
 
P

Protoman

How do I access the induvidual elements of a vector if I have no idea
how many there are?
 
M

Mark P

Protoman said:
OK here's the input function that doesn't abort on bad data:

template<class T>
void input(vector<T>& v)
{
start:
cout << "Enter the number of items: " << endl;
int num;
cin >> num;
if(num==0)
{
cout << "Try again, with a number this time ";
goto start;
}
else if(!cin)
{
cout << "Try again, with a number this time ";
goto start;
}
else
for(int i=0;i<num;++i)
{
start2:
cout << "Enter a number: ";
T temp;
cin >> temp;
if(!cin)
{
cout << "Try again, with a number this time ";
goto start2;
}
else
v.push_back(temp);
}
}

But it keeps displaying the same message over and over again; what's
wrong? Thanks for the help!!! BTW, I use Learn C++ in 21 Days and
Standard C++ Bible. And my teacher told me there's a book that tells
you everything you can and can't do in C++. Could you tell me the name
of that book please? Thanks!!!

*sigh* Where to begin?

First, get a good book. Learn C++ in 21 Days is crap. I don't know
about the Bible but it's probably crap too. Try Accelerated C++ or take
a recommendation from someone who knows:

http://www.accu.org/bookreviews/public/

OK, now to your code...

First, don't use goto statements. They're confusing to read, they're
almost always unnecessary, and the cases where they may be appropriate
are rare enough to ignore. If you find yourself wanting to use goto
statements, think harder about the structure of your code.

The specific problem that you're encountering is that you're using the
input stream cin after it has entered some sort of "bad" state-- invalid
input, end of file, etc. The solution is to clear it, as in
cin.clear(), before attempting to read anything else from it.
Incidentally, this is discussed nicely in Accelerated C++ which, in
fact, has a function that does exactly what you're doing: reading values
into a vector.

I'm not sure why you have your function ask the user how many entries
there are. Why not let the user enter an EOF when he's done? (EOF =
end of file. On Unix, usually ctrl-D, on Win usually ctrl-Z.)
Something like this: (untested code!)

// Reads user values of type T into v until EOF.
// Returns number of values inserted.
template <class T>
int input(vector<T>& v)
{
int count = 0;
T num;
while (true) // keep reading until we break
{
cout << "Enter a number: ";
if (cin >> num) // valid entry
{
v.push_back(num);
++count;
}
else // EOF or bad entry
break;
cin.clear(); // reset stream from EOF or bad value state
}
return count;
}


-Mark
 
F

Francis Glassborow

John Harrison said:
It works, but the idiots aren't going to be very happy when the program
aborts. I would have suggested some sort of error recovery, 'Hey idiot!
Please enter the number again', that kind of thing.

Indeed, abort and exit both have vulnerabilities in that they leave the
stack unwound which may have consequences. Throwing an exception is
probably better in C++. However when dealing with keyboard input it is
almost always better to give the user a chance to try again. By default
I allow three tries before deciding that input is being provided by a
cat walking over the keyboard.
 
F

Francis Glassborow

John Harrison said:
There is nothing that cannot be done in C++, it is a general purpose
language. Of course there are somethings that are easy to do and some
that are difficult, compared to other languages.

Direct keyboard reading in C++ is an example of something that is nearly
impossible without augmenting it with a special purpose library. I say
almost impossible because you could, in theory (but I have never seen it
used in practice) write a routine in assembler using the asm keyword.
 
K

Karl Heinz Buchegger

Protoman said:
OK, here we go, inputting's a seperate function now:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <numeric>
using namespace std;
void input(vector<long double>& v)
{
cout << "Enter the number of items: " << endl;
int num;
cin >> num;
for(int i=0;i<num;++i)
{
cout << "Enter a number: ";
long double temp;
cin >> temp;
v.push_back(temp);
}
}

long double mean(vector<long double>& v)
{
input(v);

That call does not belong here.
Remember: One function - one responsibility.

As it is now, the function mean() is responsible for both:
the input thing and the calculation thing.

Why not call input in main() ?
This would free mean from that job, and would allow you to use
mean in other ways. Eg. some other computation comes up with a bunch
of numbers and you need the mean of those. Put those numbers
in a vector and calling mean() would do the job nicely. But then
your mean kicks in and wants some numbers from the user :)
 
P

Protoman

I've used those books, and my teacher, whose is (really; I'm not lying)
a top programmer at Bell Labs, says those two are great books for a
beginner; I've got others. And thanks for the tip. And how to I access
induvidual items from a vector when I have no idea how many there are?
 
B

BobR

Protoman wrote in message
. And how to I access
induvidual items from a vector when I have no idea how many there are?

That's why you use vectors, you *do* know how many there are!!

// #includes here
std::vector<int> Vint;
for(int i(0); i < 10; ++i){ Vint.push_back( i );}

for(size_t i(0); i < Vint.size(); ++i){
std::cout << Vint.at( i ) << std::endl;
}

int Number5( Vint.at( 4 ) ); // hope & pray
try{ Number5 = Vint.at( 12 );} // may throw exception
catch(...){ std::cout << "Ouch!" << std::endl;}
size_t indx(2);
if( indx < Vint.size() ){
Number5 = Vint.at( indx );
}

[ Untested. ]
 
F

Francis Glassborow

I've used those books, and my teacher, whose is (really; I'm not lying)
a top programmer at Bell Labs, says those two are great books for a
beginner; I've got others. And thanks for the tip. And how to I access
induvidual items from a vector when I have no idea how many there are?

He may be a great programmer but he is not a great judge of books.
 
R

Robbie Hatley

Some weeks ago, in a thread in this group and one other,
You are thinking of 'exit()', BUT, don't use that for normal program
termination. It's intended as an 'emergency exit' (it's possible to shoot
yourself in the foot - or worse!).

I'm curious, what do you figure is wrong with exit()? I use that a lot
in my programs if the program needs to terminate somewhere other than
the last line (usually "return 0;") of main(). I consider it the
"terminate program after exceptional event (not necessarily error)"
function.

For example:

int main(int Tom, char* Jerry[])
{
// ... dozens of lines of code ...
if (bHelp) // if user used a "-h" or "--help" switch
{
Help(); // Print instructions,
exit(777); // and exit program.
}
// ... dozens more line of code, mostly calls to functions that
// do most of the work ...
return 0;
}

I sure like that a lot better than:

int main(int Tom, char* Jerry[])
{
// ... dozens of lines of code ...
if (bHelp) // if user used a "-h" or "--help" switch
{
Help(); // Print instructions,
goto End; // and go to end.
}
// ... dozens more line of code, mostly calls to functions that
// do most of the work ...
End:
return 0;
}

And what if a function other than main needs to terminate the app in
an orderly fashion?

void
ReadFileToVector
(
std::string const & FileName,
std::vector<std::string> & Text
)
{
// ... some code ...
(if !InputFileStream) // if we can't open the file,
{
cerr << "Error: Cannot open file " << FileName << " for input!" << endl;
exit(666); // Crash and burn, in an orderly way.
}
// ... some more code ...
return 0;
}

I don't see any other orderly way to exit in a case like that.

As I understand it, exit() does basic clean-up (destructs
objects, closes files, etc.), unlike abort() and terminate(),
which die much more messily.

So, what's to dislike about exit()? Does Bob R. or anyone
else here know of any reasons NOT to freely use this function?


Curious,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
 
A

Alf P. Steinbach

* Robbie Hatley:
I don't see any other orderly way to exit in a case like that.

Orderly -- with stack unwinding -- throw an exception of a type only
caught by a catch in 'main'.

As I understand it, exit() does basic clean-up (destructs
objects, closes files, etc.), unlike abort() and terminate(),
which die much more messily.

§3.6.1/4, the standard guarantees that you do not get stack unwinding.
 
R

Robbie Hatley

Alf P. Steinbach said:
* Robbie Hatley:

Orderly -- with stack unwinding -- throw an exception of a type only
caught by a catch in 'main'.


§3.6.1/4, the standard guarantees that you do not get stack unwinding.


::: reads standard :::

Fascinating. I didn't realize that. So if I want to avoid
leaking memory in, say, a file-io function that crashes because
some dork plugged in the wrong file name, I should probably NOT
exit(), but do:


// In ReadFile():
if (!InputFileStream)
{
FileIOException tantrum;
throw tantrum;
}


// In main():
try
{
ReadFile();
}
catch (FileIOException)
{
cerr << "Had a lil problem there, Charly!" << endl;
cerr << "ENTER THE RIGHT FILE NAME NEXT TIME, YOU DORK!!!" << endl;
return 1; // or maybe just set a flag, leading to re-try of ReadFile()
}


Less leaky?


And out of curiousity, what if I'm a bad boy and exit() with
100MB of stuff on the stack? Does the OS (eg, Win2k) reclaim
that? Or is that 100MB off-line until I shut down or push "reset"?
Or is this OS dependent?


Cheers,
Robbie Hatley
Tustin, CA, USA
email: lonewolfintj at pacbell dot net
web: home dot pacbell dot net slant earnur slant
 
K

Kai-Uwe Bux

Robbie Hatley wrote:

[snip]
And out of curiousity, what if I'm a bad boy and exit() with
100MB of stuff on the stack? Does the OS (eg, Win2k) reclaim
that? Or is that 100MB off-line until I shut down or push "reset"?
Or is this OS dependent?

It is OS dependent. The C++ standard does not specify *any* way of returning
memory to the OS / execution environment, neither during program execution
nor upon termination.

However, I would consider it a bug in the OS if it did not reclaim all
resources left without owner from a process dying.


Best

Kai-Uwe Bux
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top