Create a Microsoft Visual Studio C++ WIN32 project. Create it as a Console Appli
ID: 3548241 • Letter: C
Question
Create a Microsoft Visual Studio C++ WIN32 project. Create it as a Console Application, and an Empty Project. Add a single .cpp file only, and write the C++ code in that file to do the following:
1. Create an STL vector object, and store the first 30 Fibonacci numbers in the vector. Display the vector.
2. Create an STL list object and an iterator to go with it. Add 20 random numbers to the list. Display the list using the iterator. Sort the list with the STL sort() method (mylist.sort() for a list object called mylist). Display the list from smallest to largest, and then from largest to smallest using iterators.
3. Write a struct called orderedPair that includes two doubles, x and y. Create an STL list of orderedPair items. Populate the list with 10 pairs of random doubles, where each x and y is in the range 0.0 to 99.9 and has 1 decimal point of accuracy. Using an iterator, display the list in the format (x1, y1), (x2, y2), (x3, y3),.
Explanation / Answer
#include <iostream>
#include <vector>
#include <list>
using namespace std;
int main()
{
/* 1) Create an STL vector object, and store the first 30 Fibonacci numbers in the vector.
Display the vector.
*/
vector<int> *fibvec = new vector<int>();
int a = 0, b = 1, t = 0;
for(int i = 0; i < 30; i++) {
fibvec->push_back(a);
t = a;
a = b;
b = t + b;
}
cout << endl << "Fibanocci series:" << endl;
for (vector<int>::iterator it = fibvec->begin() ; it != fibvec->end(); ++it)
cout << *it << ' ';
cout << endl;
/* Create an STL list object and an iterator to go with it
*/
list<int> *randlist = new list<int>();
for(int i = 0; i < 20; i++)
randlist->push_back(rand());
cout << endl << "Random list:" << endl;
for (list<int>::iterator it=randlist->begin(); it != randlist->end(); ++it)
cout << ' ' << *it;
cout << endl;
randlist->sort();
cout << endl << "Sorted List(smallest to largest) :" << endl;
for (list<int>::iterator it=randlist->begin(); it != randlist->end(); ++it)
cout << ' ' << *it;
cout << endl;
cout << endl << "Sorted List(largest to smallest) :" << endl;
for (list<int>::reverse_iterator rit=randlist->rbegin(); rit!=randlist->rend(); ++rit)
cout << ' ' << *rit;
cout << endl;
/* Write a struct called orderedPair that includes two doubles, x and y
*/
struct orderedPair {
double x;
double y;
};
list<struct orderedPair> *oplist = new list<struct orderedPair>();
for(int i = 0; i < 10; i++) {
struct orderedPair op = { (double) (rand() % 1000) / 10, (double) (rand() % 1000) / 10 };
oplist->push_back(op);
}
cout << endl << "Ordered pair list: " << endl;
for (list<struct orderedPair>::iterator it=oplist->begin(); it != oplist->end(); ++it)
cout << "(" << it->x << ", " << it->y << ") ";
cout << endl;
return 0;
}