在矢量中搜索项目

Search item in a vector

本文关键字:搜索 项目      更新时间:2023-10-16

我想在我的结构中找到一个元素(姓氏)

struct student
{
    char name[20];
    char surname[20];
    int marks;
};

Ofc从键盘定义矢量和搜索元素

vector <student> v;
char search_surname[20];

我是按功能输入元素:

    int size = v.size();
    v.push_back(student());
    cout << "Input name: " << endl;
    cin >> v[size].name;
    cout << "Input surname: " << endl;
    cin >> v[size].surname;
    cout << "Input marks: " << endl;
    cin >> v[size].marks;

现在,例如,当我的结构中有三个姓氏(牛顿、爱因斯坦、帕斯卡尔)时,我想找到姓牛顿,并用牛顿(名称、姓氏、标记)计算结构的所有细节。我不知道该怎么办。

一种暴力方法:

for(vector <student>::iterator it = v.begin(); it != v.end(); it++)
{
    if (strcmp(it->surname, "newton") == 0)
    {
        cout << "name = " << it->name << endl;
        cout << "surname = " << it->surname << endl;
        cout << "marks = " << it->marks << endl;
    }
}

请将#include <cstring>添加到代码中,以便使用strcmp()

使用STL,可以使用<algorithm>:中的std::find_if

std::vector<student> v;

auto it = std::find_if(v.begin(), v.end(), [](const student& s)
              {
                  return strcmp(s.surname, "newton") == 0;
              });
if (it != v.end()) {
    std::cout << "name = " << it->name << std::endl;
    std::cout << "surname = " << it->surname << std::endl;
    std::cout << "marks = " << it->marks << std::endl;
}

注意:我建议使用std::string而不是char[20],因此条件将变为return s.surname == "newton"

我最近使用了库<算法>

此函数返回一个迭代器,并在返回值不是end()时指示find。