Outputting elements of an array with a for loop?

How would I write a for loop to output the elements of this vector while being general with the number of elements (without specifying the size of the array).

1
2
3
4
5
6
7
8
9
10
11
  vector<int> myList( 5 );
int i;
unsigned int length;
 
myList[ 0 ] = 3;
for ( i = 1; i < 4; i++ )
     myList[ i ] = 2 * myList[ i – 1 ] – 5;
 
myList.push_back( 46 );
myList.push_back( 57 );
myList.push_back( 35 );
Hello.

You can use an iterator for the vector. Check out the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <vector>
using namespace std;

int main(){
	vector<int> myList;
	
	myList.push_back(10);
	myList.push_back(20);
	myList.push_back(34);
	
	for(vector<int>::iterator iter= myList.begin(); iter != myList.end(); iter++)
		cout<< *iter<< endl;
		
	exit(EXIT_SUCCESS);
}


Here, you don't need the size of the vector.

Greetings.
Last edited on
Topic archived. No new replies allowed.