Re: copying Vector elements into Dynamic Array
On 2007-07-24 08:26, arnuld wrote:
/* C++ Primer - 4/e
* chapter 4- Arrays & Pointers, exercise 4.28
* STATEMENT
* write a programme to read the standard input and build a vector
of integers from values that are read. allocate an array of the same
size as the vector and copy elements from the vector into the array
*/
#include <iostream>
#include <vector>
int main()
{
int iv;
std::vector<int> ivec;
while(std::cin >> iv)
{
ivec.push_back(iv);
}
const size_t arr_sz = ivec.size() + 1;
No need to add one extra, see below.
int* pdarr = new int[arr_sz];
int* pbegin = pdarr;
/* we will use "pbegin" to print the array elements later */
/* assign elements from vector to the dynamic array */
for(std::vector<int>::const_iterator iter=ivec.begin();
iter != ivec.end(); ++iter)
{
*pdarr++ = *iter;
}
Often when iterating through vectors I find that the index of the index
of the current element is of interest for more purposes than indexing
into the vector, and in these cases I tend to not use iterators:
for (size_t i = 0; i < ivec.size(); ++i)
{
pdarr[i] = ivec[i];
}
this way you get slightly cleaner code, and you don't need the two
pointers to the array.
/* printing the elements of arrar */
std::cout << "printing array elements: ";
for(int* q = pbegin; q != pbegin + arr_sz; ++q)
{
std::cout << *q << " ";
}
One again, I'd probably use indexing. It puts more emphasis on the fact
that I'm going through an array and hides the fact that I'm playing with
pointers.
std::cout << std::endl;
return 0;
}
You forgot to free the array.
======== OUTPUT ===========
~/programming/cpp $ g++ -ansi -pedantic -Wall -Wextra ex_04-28.cpp
~/programming/cpp $ ./a.out
2
3
-9
8
printing array elements: 2 3 -9 8 0
~/programming/cpp $
i have 2 questions:
1.) i have used "vecotor size + 1" for array size but i did not enter last
character as NULL. does the programme add it to the end of array itself
automatically ?
2.) output contains an extra integer in the end, the zero, 0. i am not
letting the pointer slipping-off the end of array because i used "q !=
pbegin + arr_size" then from where the zero came ?
You seem to be confusing things, C-style arrays are not 0-terminated, if
that was the case how would you tell the difference between an element
in the middle of an int-array that was 0 and the end? You are thinking
of C-style strings, which are 0-terminated char-arrays.
--
Erik Wikstr??m