Monday, May 24, 2010

C++ Program Question?

The question is:





Write a complete program that reads in some unknown number of positive integers from standard input (keyboard) into a vector. Then output all values to standard output (terminal) in reverse order (with one space between each value). The user will type a -1 to signal that they are through inputting positive integers. Do not output the -1.


For example, if the values read in are in this order: 1 3 5 2 9 then the output would be: 9 2 5 3 1


Do not output anything other than the values in the vector. In other words, do not prompt the user for input. Just assume the user knows to input some number of positive integers and a -1 to finish.





This is my code:





#include %26lt;vector%26gt;


#include %26lt;iostream%26gt;


using namespace std;





int main()


{


vector%26lt;double%26gt; Vec;


int vec_size = 0;


while (Vec[vec_val = -1)


{


cin %26gt;%26gt; Vec[vec_val];


vec_val ++;


}


for(vec_size; vec_size %26gt;= 0; vec_size--) cout %26lt;%26lt; Vec[vec_size] %26lt;%26lt; " ";


return 0;


}

C++ Program Question?
#include%26lt;vector%26gt;


#include%26lt;iostream%26gt;





using namespace std;


double val = 0;


vector%26lt;double%26gt; vec;


while(val != -1){





cin %26gt;%26gt; val;





vec.push_back(val);


};





int reverse_index = vec.size() -1;





vector%26lt;double%26gt; reverse(vec.size(), 0);





for(int i =0; i %26lt; vec.size(); ++i){





reverse[reverse_index--] = vec[i];





};





for(int i = 0; i %26lt; reverse.size(); ++i){





cout %26lt;%26lt; reverse[i];


};





return 0;





}











you don't even have to copy them if you don't want to you can just do








for(int i = vec.size() -1; i %26gt; 0; --i){





cout %26lt;%26lt; vec[i];





};














vectors have a bunch of built in functions such as size() push_back()....





check em out


http://www.cppreference.com/cppvector/in...


No comments:

Post a Comment