How to print vector with for_each in C++

2 Answers

0 votes
#include <iostream>
#include <vector>
#include <algorithm>

void print_vec(int elem)
{
	std::cout << elem << ' ';
}

int main()
{
	std::vector<int> vec;

	for (int i = 1; i <= 5; i++) {
		vec.push_back(i);
	}

	for_each(vec.cbegin(), vec.cend(),  print_vec);

	std::cout << std::endl;
	
	return 0;
}

/*
run:

1 2 3 4 5

*/

 



answered Dec 31, 2017 by avibootz
0 votes
#include <iostream> 
#include <vector>
#include <algorithm>

using std::vector;
using std::cout;  
using std::endl;

void print(int n) {
	cout << n << " ";
}

int main()
{
	vector<int> vec{ 13, 12, 300, 1, 98 };

	for_each(vec.begin(), vec.end(), print);

	cout << endl;

	return 0;
}

/*
run:

13 12 300 1 98

*/

 



answered Apr 27, 2018 by avibootz

Related questions

1 answer 169 views
1 answer 107 views
1 answer 187 views
1 answer 135 views
135 views asked Apr 27, 2018 by avibootz
1 answer 166 views
1 answer 94 views
...