首页 > 解决方案 > 如何使用值获取结构的索引

问题描述

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,索引是什么

标签: c++

解决方案


您可以std::find_ifalgorithm库中使用:

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。代码中的裸news 只是错误的来源(即内存泄漏)。


推荐阅读