我有一些包含 4 个字段的结构 我在某个数组(不是映射)中保留了这个结构的 100 个实例,我想找到 根据特定字段在数组中的一些元素
我可以扫描所有但我可以使用 std::find
或其他方式(我知道 find 扫描所有数组,但我认为使用 find 会很简单。)
代码:
struct MyElement
{
std::string val1;
std::string val2;
std::string val3;
}
std::array<MyElement, 100> _myArray;
// need to find the first element that the val2 is 'Go'
bool found = false;
for(int i = 0; i < 100 ; i++)
{
if(_myArray[i].val2 == 'Go')
{
found = true;
break;
}
}
最佳答案
如果 MyElement
实例的序列未排序,则您无法避免对特定对象进行线性扫描。 std::find_if
是你的 friend ,你可以用它来避免手写循环,它在第一次匹配时停止。示例:
#include <algorithm>
#include <cassert>
std::array<MyElement, 100> _myArray;
_myArray[50] = { "...", "Go", "..." };
const auto lookup = std::find_if(_myArray.cbegin(), _myArray.cend(),
[](const MyElement& e){ return e.val2 == "Go"; });
assert(lookup == _myArray.cbegin() + 50);
如果您需要重复查找元素,先对序列进行排序然后使用二分查找可能会更有利:
const auto binaryPred = [](const MyElement& e1, const MyElement& e2){
return e1.val2 < e2.val2; };
std::sort(_myArray.begin(), _myArray.end(), binaryPred);
const auto fasterLookup = std::lower_bound(_myArray.cbegin(), _myArray.cend(), "Go",
[](const MyElement& e, const auto& value){ return e.val2 == value; });
但是,如果不知道确切的情况,就无法预测这是否会奏效。如果不确定,请衡量这两种方法。
关于c++ - 如何根据某个字段在数组中查找元素(无需使用 for 循环扫描整个数组),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54286859/