



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




-1.3, 5.2, 8.7, -4.5, 0.0, 7.8, -9.1, 3.5, 6.
then the resulting vector of negative numbers should contain
-1.3, -4.5, -9.
and the resulting vector of positive numbers should contain
5.2, 8.7, 7.8, 3.5, 6.
Start this problem by writing the function prototype as you think it should appear and then write the code.
Solution:
void copy_pos_neg( const vector
(a) State two reasons why are standard library vectors are preferrable to ordinary C++ arrays.
Solution: Here are the primary answers I’m hoping to see: (1) Vectors aren’t fixed in size, and (2) vectors know their own size. A number of other answers are possible, primarily built around the member functions for vectors.
(b) When passing a vector to a function why is using pass-by-value usually a bad idea? Solution: The answer should state that the (entire) vector is copied each time the function is called. They can also, instead, mention that changes to the vector are not preserved.
The function prototype should be
int is_less( int m, int n)
Solution:
int is_less( int m, int n) { if ( n == 0 ) return false; else if ( m == 0 ) return true; else return is_less( m-1, n-1 ); }
class Robot { public: Robot( float x0, float y0, float in_dx, float in_dy, float rad );
void step(); bool inside_walls( float xbound, float ybound ) const; float distance_to( const Robot& r1 ) const;
private: float x, y; // Robot’s current position float dx, dy; // Robot’s step float radius; // Robot’s radius --- not all robots have the same radius };
(a) Show the implementation of the step member function, which moves the robot a single step for a single time unit. Solution: void Robot::step() { x += dx; y += dy } (b) Show the implementation of the inside walls member function. It should return true if the robot is within the bounds of the walls and is at least radius away from the walls. Solution: void Robot::inside_walls( float xbound, float ybound ) const { return radius < x && x < xbound-radius && radius < y && y < ybound-radius; }
(c) Show the implementation of the distance_to member function which returns the distance between the robots. Here the distance is the Euclidean distance between the centers minus the radii of the two robots. If the resulting distance is negative, the function should return 0. As an example, if one robot is at (0, 0) with radius 1.5 and the other robot is at (3, 4) with radius 2.5, then the function should return 1 since the distance between the centers is 5 and the two radii sum to 4. You may use the sqrt function. Solution: float Robot::distance_to( const Robot& r1 ) const { float dx = x - r1.x; float dy = y - r1.y; float dist = sqrt(dxdx + dydy) - radius - r1.radius; if ( dist < 0 ) return 0; else
return dist; }
for ( int i=0; i<matches.size(); ++i ) cout << " " << matches[i] << ’\n’; }