根据字符串从矢量获取特定项
get a particular item from vector based on string
我有一个包含一堆数据类型的通用结构。例如
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;
相关文章:
- 获取字符串的长度并将其分配给数组
- 调用CreateProcess()并获取字符串的返回值
- 你如何从 Boost Spirit X3 词法解析器中获取字符串?
- 使用 ReadProcessMemory 获取字符串值的访问冲突
- 如何从输入中获取字符串向量?
- 如何获取字符串输入n次?
- property_tree获取字符串形式的数组值
- 使用 ctypes 和 wchar_t 时如何从 C++ 获取字符串到 python?
- 获取字符串大小的各种方法之间的比较
- 方法获取字符串
- 在getline()之后获取字符串
- 为什么我的拆卸C 代码使用指令指针和偏移来获取字符串文字
- 无法使用 Poco 获取字符串的路径
- 如何在qtablewidget中获取字符串的行号
- 如何获取字符串和字节进行比较
- 恒定字符阵列的获取字符串长度函数(strlen)不是恒定表达式
- 我需要创建一个函数来获取字符串中的这些数字
- 如何从地址获取字符串?
- 为什么即使尚未初始化,获取字符串[0]也是有效的?
- 获取C++字符串的位