Thread: processing dynamic arrays

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Ireland
    Posts
    8,446

    processing dynamic arrays

    Hello all,

    While learning about dynamic arrays, I'm asked by C++ primer to do the following exercise:

    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;
    }
    Last edited by Mario F.; 06-04-2006 at 09:49 AM.
    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and freeing dynamic arrays
    By circuitbreaker in forum C++ Programming
    Replies: 8
    Last Post: 02-18-2008, 11:18 AM
  2. Replies: 16
    Last Post: 01-01-2008, 04:07 PM
  3. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM
  4. dynamic arrays and structures
    By godofbabel in forum C++ Programming
    Replies: 1
    Last Post: 10-13-2002, 03:45 PM