c++ - 搜索记录集/更新值
问题描述
我使用结构、向量创建了一个记录集并添加了几条记录。这是执行此操作的代码。这应该在 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
,但我不确定,因为这是我第一次处理结构和向量。studentName 是常量(我只需要在启动时加载一次),studentSlot 可以在运行时更改。我不知道如何改变它。它可能需要我删除 const char*,做一些 strcpy 事情或其他事情,但我被困在那里。简而言之,有 3 件事我需要一点帮助
1) 通过 studentName 搜索/查找记录
2)能够更新studentSlot
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) {
...
推荐阅读
- python-3.x - Python3:如何从 url 获取标题 eng?
- here-api - HERE API:在针对前端域进行保护时使用后端的 app_id 和 app_code
- sql-server - 消息 102,第 15 级
- vue.js - 如何使用 vue.js 按日期对消息进行分组?[Vue 警告]:你可能有一个无限更新循环
- kubernetes - k8s中admission webhook和controller manager的优先级是多少?
- sql - 将 nvarchar 值转换为数据类型 int 时转换失败 - 错误消息
- sharepoint - 使用 pnpPowershel 的 Sharepoint 在线列表和项目级别权限
- c# - 临时禁用 ConcurrencyCheck 属性
- node.js - 时间间隔上的 AWS Lambda Postgres 数据库连接问题
- java - 如何在我的 RestController 中使用接口属性在我的请求处理程序中返回数据