processing dynamic arrays
Hello all,
While learning about dynamic arrays, I'm asked by C++ primer to do the following exercise:
Quote:
Write a program to read the standard input and build a vector of ints from values that are read. Allocate an array of the same size as the vector and copy the elements from the vector into the array.
I came up with what you can see below. I would like to know, is it possible to simplify the for loop where I assign to the dynamic array? Specifically, can I do this without creating a pointer to the dynamic array while making sure I do not overflow?
Code:
#include <cstdlib>
#include <iostream>
#include <vector>
#include <iterator>
int main()
{
using namespace std;
int input;
vector<int> iv;
while (cin >> input) {
iv.push_back(input);
}
cout << endl;
for (vector<int>::const_iterator i = iv.begin(); i != iv.end(); ++i) {
cout << *i << "\t";
}
cout << endl;
int *p = new int[iv.size()];
vector<int>::size_type i = 0;
for (int *pp = p; pp != p + iv.size(); ++pp, ++i) {
*pp = iv[i];
cout << *(p + i) << "\t";
}
cout << endl;
delete[] p;
system("PAUSE");
return 0;
}