练习10.1

发布时间 2023-07-17 22:54:54作者: yuzuki_n

头文件algorithm中电仪了名为count的函数,它类似find,接受一对迭代器和一个值作为参数,count返回给定值在序列中出现的次数。编写程序,读取int序列存入vector中,打印有多少元素等于给定值

我的做法

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> vec { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4 };
    auto cnt = count(vec.begin(), vec.end(), 4);
    std::cout << cnt << std::endl;
}

书上的做法

#include <algorithm>
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

int main(int argc, char* argv[])
{
    ifstream in(argv[1]);
    if (!in)
    {
        cout << "打开文件失败!" << endl;
        exit(1);
    }

    vector<int> vi;
    int val;
    while (in >> val)
        vi.push_back(val);

    cout << "请输入要搜索的整数" << endl;

    cin >> val;
    cout << count(vi.begin(), vi.end(), val) << endl;
    return 0;

}