Cho vector và giá trị mục tiêu (target). Đếm số phần tử trong vector bằng target hoặc thỏa mãn điều kiện.
Ví dụ
vec = {1, 2, 3, 4, 4, 4, 4}, target = 4 → count = 4
vec = {1, 2, 3}, target = 4 → count = 0
Phương pháp
Sử dụng hàm count() trong STL
Ví dụ minh họa (C++)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> myvector{ 1, 2, 3, 4, 4, 4, 4, 4 };
int target = 4;
int res = count(myvector.begin(), myvector.end(), target);
cout << "Target is: " << target << "\nCount is: " << res << endl;
return 0;
}
Đầu ra
Target is: 4 Count is: 5