How to count bool vector true and false values in C++

1 Answer

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

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

void print(vector<bool> vec) {
	for (int i = 0; i < vec.size(); i++)
		cout << boolalpha << vec[i] << " ";
	cout << endl;
}

int main()
{
	vector<bool> vec;

	srand((unsigned)time(NULL));

	for (int i = 0; i < 13; i++) {
		if (rand() % 2)
			vec.push_back(true);
		else
			vec.push_back(false);
	}

	print(vec);

	int total_true = count(vec.begin(), vec.end(), true);
	int total_false = count(vec.begin(), vec.end(), false);

	cout << total_true << endl;
	cout << total_false << endl;

	return 0;
}


/*
run:

true true false true true true true false true true false false true
9
4

*/

 



answered May 18, 2018 by avibootz

Related questions

...