c++ - 如何使用值获取结构的索引
问题描述
struct prediction
{
string address;
long int index;
};
struct prediction *bp = new struct prediction[1300];
bp[0].index =0;
bp[0].address =2553278;
bp[1].index =1;
bp[1].address =1356;
如何根据地址获取 bp 的索引,即如果地址 = 1356,索引是什么
解决方案
您可以std::find_if
从algorithm
库中使用:
struct prediction *bp = new struct prediction[1300];
bp[0].index =0;
bp[0].address =2553278;
bp[1].index =1;
bp[1].address =1356;
prediction* ptr_to_searched = std::find_if(bp, bp + 1300, [](const prediction& p) { return p.address == 1356;});
if( ptr_to_searched != bp + 1300 )
{
size_t index = static_cast<size_t>(ptr_to_searched - bp);
}
else
{
// Not found
}
此外,您不应该通过new
. 改为使用std::vector
。代码中的裸new
s 只是错误的来源(即内存泄漏)。
推荐阅读
- wso2-am - 在 wso2 api manager 3.2.0 的端口和 Thrift SSL 端口上使用二进制 SSL 传输的位置
- javascript - Vue中如何控制多个复选框
- oracle - PL/SQL 根据动态表名创建视图
- google-apps-script - 需要使用应用程序脚本从 Monthwise 到 datewise 对日期进行排序
- flutter - Flutter ios无法构建
- amazon-web-services - 如何使用 AWS athena 在特定事件之前和之后提取时间序列数据?
- reactjs - Nx.dev Gatsby 在插件 gatsby-plugin-translate-urls 中抛出错误 - 不支持实验性语法“jsx”
- google-cloud-platform - BigQuery 自动检测架构问题 int64 与 float64
- intellij-idea - IntelliJ 中是否还有其他用于 Java VM 系统属性的设置?
- c# - asp net core 返回具有空属性的json(非空)