在记录集/更新值中搜索

search in record set / update value

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

我使用结构体、向量创建了一个记录集,并添加了几条记录。这是执行此操作的代码。这应该按原样运行 - 在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)能够更新studentSlotwasPresent

通过一些研究和实验,我发现我可以这样做来改变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) {
...