在记录集/更新值中搜索
search in record set / update value
我使用结构体、向量创建了一个记录集,并添加了几条记录。这是执行此操作的代码。这应该按原样运行 - 在Arduino/ESP8266/ESP32上。
#include <string>
#include <vector>
struct student {
std::string studentName; // I only load this once at startup. So can be const
std::string studentSlot; // <= This should be updateable
bool wasPresent; // <= This should be updateable
student(const char* stName, const char* stSlot, bool stPresent) :
studentName(stName),
studentSlot(stSlot),
wasPresent(stPresent)
{}
};
std::vector<student> studentRecs;
void setup() {
delay(1000);
Serial.begin(115200);
// Add couple of records
student record1("K.Reeves", "SLT-AM-03", false);
student record2("J.Wick", "SLT-PM-01", true);
studentRecs.push_back(record1);
studentRecs.push_back(record2);
}
void loop() {
Serial.println();
// Get the size
int dsize = static_cast<int>(studentRecs.size());
// Loop, print the records
for (int i = 0; i < dsize; ++i) {
Serial.print(studentRecs[i].studentName.c_str());
Serial.print(" ");
Serial.print(studentRecs[i].studentSlot.c_str());
Serial.print(" ");
Serial.println(String(studentRecs[i].wasPresent));
}
// Add a delay, continue with the loop()
delay(5000);
}
我能够使用 for 循环读取单个记录。我不确定这是否是最好的方法,但它确实有效。
我需要能够在这个记录集上做几件事。
1) 按studentName
搜索/查找记录。我可以通过循环找到它,但这对我来说效率低下+丑陋。
2)能够更新studentSlot
和wasPresent
通过一些研究和实验,我发现我可以这样做来改变wasPresent
studentRecs[0].wasPresent = false;
同样,我不确定这是否是最好的方法,但它有效。我希望能够更改studentSlot
,但我不确定,因为这是我第一次处理结构和向量。学生名称是常量(我只需要在启动时加载一次),学生插槽可以在运行时更改。我不知道如何改变这一点。它可能需要我删除常量字符*,做一些 strcpy 事情或其他事情,但我被困住了。简而言之,我需要3件事的帮助
1) 按学生姓名搜索/查找记录
2)能够更新学生插槽
3) 删除所有记录。注意:我刚刚发现studentRecs.clear()
这样做
我不确定我是否能够足够清楚地解释这一点。所以任何问题请拍摄。谢谢。
好吧,我认为你最好的选择是使用for
循环来搜索studentName
。根据您使用的C++修订版:
student searchForName(const std::string & name)
{
for (auto item : studentRecs)
{
if (item.studentName == name)
return item;
}
return student();
}
或者,如果您被限制在 C++11 之前:
student searchForName(const std::string & name)
{
for (std::size_t cnt = 0; cnt < studentRecs.size(); ++cnt)
{
if (studentRecs[cnt].studentName == name)
return item;
}
return student();
}
其余的非常相似。
顺便说一句:您可以更改:
...
// Get the size
int dsize = static_cast<int>(studentRecs.size());
// Loop, print the records
for (int i = 0; i < dsize; ++i) {
...
自:
...
// Loop, print the records
for (std::size_t i = 0; i < studentRecs.size(); ++i) {
...
相关文章:
- 从C++本机插件更新Vector3数组
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 有根的二进制搜索树.保留与其父级的链接
- 在C++中搜索嵌套多映射值
- cpp二进制搜索问题,计算给定数组中输入元素的出现次数
- 二进制搜索树叶数问题
- 为什么二进制搜索在我的测试中不起作用
- cmake更新缓存的变量
- 正在尝试重载二进制搜索树分配运算符
- 更新到莫哈韦后出现cmath错误
- c++binary_search函数排序数组(流行名称搜索)出现问题
- 向量上的线性搜索
- 如何在动态数组上使用搜索函数
- OpenMP:并行更新数组总是需要减少数组吗
- 为什么我的变量没有更新,我的 LED 没有亮起?
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 在动态链接中,.exe如何知道在更新库时在哪里搜索库?
- 在记录集/更新值中搜索
- O(log n) 索引更新和搜索
- 搜索和更新整数值列表最快的数据结构是什么?