For example, how many in the vector of integers, triples?
- Let's take a look at your previous questions this time and find the answer in my answers. The function has a very simple and clear name. Although no one bothers to use std :: accumulate :) - KoVadim
- Function find, probably. - perfect
- it will have to be called in a loop. But there is a more direct way. One function. - KoVadim
- accumulate and in its last parameter find? - perfect
- So you can write (although just like the last parameter find can not be used). So I do not understand, is it really difficult to open help on the std :: find function and find a link to a friend there that solves the problem? Or do we not know English at all? - KoVadim
|
1 answer
To calculate how many times a given value is found in a vector or another container, the C ++ 14 option:
#include <algorithm> // std::count #include <iostream> #include <iterator> // std::cbegin, std::cend #include <vector> int main() { using namespace std; vector<int> v = { 1, 3, 2, 3, 4 }; cout << count(cbegin(v), cend(v), 3) << endl; }
C ++ 11:
#include <algorithm> // std::count #include <iostream> #include <vector> int main() { using namespace std; vector<int> v = { 1, 3, 2, 3, 4 }; cout << count(v.cbegin(), v.cend(), 3) << endl; }
More common C ++ 11 option:
#include <algorithm> // std::count #include <iostream> #include <iterator> // std::begin, std::end #include <vector> int main() { using namespace std; vector<int> v = { 1, 3, 2, 3, 4 }; cout << count(begin(v), end(v), 3) << endl; }
C ++ 98:
#include <algorithm> // std::count #include <iostream> #include <vector> int main() { using namespace std; int a[] = { 1, 3, 2, 3, 4 }; vector<int> v(a, a + sizeof(a) / sizeof(*a)); cout << count(v.begin(), v.end(), 3) << endl; }
|