Nathaniel10 34 Junior Poster

I tried to do an excercise from Stroupstrup's book. The reader is asked to reverse the
order of elements in a vector so that if originally vector[0] = 1, vector [1] = 2, and
vector[2] = 3, then new vector has newvec[0] = 3, newvec[1] = 2, and newvec[2] = 1.

Doing this through creating a new vector was straighforward. However, part b) of the
exercise requests the reader to reverse the elements WITHOUT creating a new vector.
I guess it means to reverse the elements of the original vector. Stroupstrup suggests
that the reader use the swap function to do this.

I researched the swap function and can't find any examples of it being used with ONE
vector. It is always used with two vectors as in

first.swap(second);

.

I thought that it might be used for swapping elements as in

first[i].swap(first[first.size() - 1 -i]);

.
But this gave me a memory allocation error.

This exercise is from the chapter (8) in which Stroustrup explains pass-by-reference.
I thought of trying to use pass-by-reference for swapping but I don't see how to formulate
that construction.

How does one use the swap function to reverse the order of elements in a vector without
using any other vectors?

Nathaniel10 34 Junior Poster

@dusktreader,

Thank you for the kind words!

The examples I saw regarding throw and catch exceptions only had one type of exception so there was only one class. That is why I didn't realize that having separate classes for each type of exception was the proper thing to do. Thanks to you and Vijayan, I have learned otherwise.

@mike,

Your suggestion works! I had to change the variable type to double, but using fmod yields the correct exception. Here is the new code I used. There is a warning about conversion from double to int since the functions yield ints but that is easily fixed.

try {
	double c = 0;
	double d = 0;
	char z = ' ';
	int result = 0;

	cout <<"Enter the set size which must be greater than zero, the subset size, \nand the type of computation.\n";
	cout <<"The set size must be greater the subset size.  \nEnter 'c' for combination or 'p' for permutation.\n";
	cout <<"Separate your entries by a space.\n";

	cin >> c >> d >> z;

	if (c <= 0 || d < 0) throw myex1;         // Negative size error.
	if (c < d) throw myex2;                   // Set size less than subet size error.
	if (z != 'c' && z != 'p') throw myex3;    // Choice other than combination or permutation error.
	if (fmod(c,1) != 0 || fmod(d,1) != 0) throw myex4;    // Non-integer error.

The comments so far have addressed the areas I needed to …

Nathaniel10 34 Junior Poster

Thank you very much for your suggestions, Vijayan. I hadn't thought that having different classes for different exceptions was an appropriate formulation.

This morning I woke up realizing why my 4th exception was crashing the program. I am using the modulo operator with a double when it can only be used with ints. I need a different test for an int.

I haven't yet learned about inheritance and enumerators. I have taken a look at chapter 7 and found what I saw very intimidating! I have noticed that Stroustrup builds on earlier programs in later exercises. Several exercises in chapters 6 and 7 ask the reader to modify programs from exercises in chapter 4.

Nathaniel10 34 Junior Poster

I am learning C++ from the Stroustrup book "Programming Principles and Practice". I have been doing the exercises in each chapter. I have gotten stuck on chapter 6. I understand the concepts of classes, constructors, functions, and 'throw and catch' error handling, but seemingly not well enough to actually write a program with these elements that compiles and runs. I have written a program for exercise 10 in chapter 6 that runs almost correctly.

It is not a pretty program and the error exception for non-integer inputs causes the program to crash with a message relating to error exception #3 instead of my intended #4. I don't know how to put all the error exceptions into the same class. Thank you in advance for your help!

N.B. You will have to change the header line if you want to run this program. The header in the program is the one Stroustrup instructs us to download from his site

#include "../../std_lib_facilities.h"

class myexception1: public exception    // Classes for handling errors.
{
  virtual const char* what() const throw()
  {
    return "The set and subset sizes must be greater than 0.\n";
  }
} myex1;

class myexception2: public exception
{
  virtual const char* what() const throw()
  {
    return "The set size must be greater than the subset size.\n";
  }
} myex2;

class myexception3: public exception
{
  virtual const char* what() const throw()
  {
    return "Either a 'c' for combination or a 'p' for permutation must be indicated.\n";
  }
} myex3;

class …
dusktreader commented: I am impressed by your ambition to self-teach c++. Nice code +1
Nathaniel10 34 Junior Poster

Hi!,

I am doing the exercises in Stroustrup's book, Programming: Principles and Practice Using C++. The 6th chapter uses a simple calculator to demonstrate Tokens and grammars. I realize that there are other calculator questions in the forum, but I did not find one that dealt directly with mine. An exercise is to add factorial capability to the calculator. That would involve altering the grammar and the tokens.

I added the exclamation point (!) to the token stream so that it would be recognized as a valid token as follows:

Token Token_stream::get()
{
    if (full) {       // do we already have a Token ready?
        // remove token from buffer
        full=false;
        return buffer;
    } 

    char ch;
    cin >> ch;    // note that >> skips whitespace (space, newline, tab, etc.)

    switch (ch) {
    case '=':    // for "print"
    case 'x':   // for "quit"
    case '(': case ')': case '+': case '-': case '*': case '/': case '{': case '}': case '!':
        return Token(ch);        // let each character represent itself
    case '.':
    case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
        {    
            cin.putback(ch);         // put digit back into the input stream
            double val;
            cin >> val;              // read a floating-point number
            return Token('8',val);   // let '8' represent "a number"
        }
    default:
        error("Bad token");
    }
}

I then added the exclamation point to the grammar list so that the expression would be recognized, as follows:

double primary()
{
    Token …
Nathaniel10 34 Junior Poster

I am teaching myself C++ with the very same book and did that very exercise yesterday.

One of the 3 'run-time' errors, as opposed to the 5 'compile-time' errors, is that not all of the possible cases are accounted for. The calculator won't recognize a certain digit as a valid token.

A second 'run-time' error is that the calculator won't perform one of the operations it is supposed to because the character that identifies the case is not the same as the operation that the calculator will actually perform.

I am still looking for the third run-time error. The calculator so far gives correct results for me.