根据字符串从矢量获取特定项

get a particular item from vector based on string

本文关键字:获取 字符串      更新时间:2023-10-16

我有一个包含一堆数据类型的通用结构。例如

struct student
{
  char* name;
  char* id;
  double avg_score;
};

现在,我有一个学生的载体。

std::vector<student> cls;

如果我有 char* id,如何获得特定的学生?还是有其他推荐的方法?可能正在维护学生证和学生结构的哈希值?

提前感谢!

您可以使用 std::find_if

const char* idToFind = "sdfsd";
std::vector<student> cls;
...
auto iter = std::find_if(cls.begin(), cls.end(), [=](student& s) {return strcmp(s.id, idToFind) == 0;});
student& s = *iter; 
int index = std::distance(cls.begin(), iter);

另外:你不能使用"class"作为变量名,我建议使用std::string而不是char*。

像这样:

int getStudentIndex(std::vector<student> students, char* id) {
    const int sz = students.size();
    for (int i=0; i<sz; i++)
        if (strcmp(students[i].id, id) == 0)
            return i;
    return -1; // not found
}

但我怀疑你可能需要 std::map

std::map会很好

struct student {
    std::string name;
    double      avg_score;
};
std::map<string, student> m;

然后,找到一个id

student found;
map<string, student>::iterator it = m.find(id);
if (it != m.end())
    found = it->second;