copy vector content into an array exercise.

I am currently working through C++ Primer 5th edition. In chapter 3, Exercise 3.42, I am asked to "Write a program to copy a vector of int's into an array of int's."

the below code works. However I have a few questions.

1) on line 16, int arr[5]; initializes an array with 5 elements. How can I alter the array so that it automatically gets/has the same size as the vector?

2) Is there a simpler way to write the program with what the book has taught so far?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 //Exercise 3.42

#include "stdafx.h"
#include <iostream>
#include <vector>

using std::vector;
using std::begin;
using std::endl;
using std::cout;
using std::end;

int main(){

	vector<int> ivec = { 1, 2, 3, 4, 5 }; //initializes vector ivec.
	int arr[5]; //initializes array "arr" with 5 null elements.
	int i1 = 0; // initializes an int named i1.
	
	for (vector<int>::iterator i2 = ivec.begin(); i2 != ivec.end(); ++i2){ 
		arr[i1] = *i2; //assigned the elements in ivec into arr.
		++i1; // iterates to the next element in arr.
	}

	for (int r1 : arr){ //range for to print out all elements in arr.
		cout << r1 << " ";
	}
	cout << endl;

	system("pause");
	return 0;
}
1. You can't. You'd need to dynamically allocate it with new[], and completely circumvent the fact that std::vector handles it all for you.

2. Not sure, but you may want to look into std::copy from the <algorithm> header:
http://www.cplusplus.com/reference/algorithm/copy/
http://en.cppreference.com/w/cpp/algorithm/copy
The <algorithm> header is a very, very useful header to be aware of.
Last edited on
Topic archived. No new replies allowed.