c++ - 如何根据某个字段在数组中查找元素(无需使用 for 循环扫描整个数组)

标签 c++ c++17

我有一些包含 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/

相关文章:

c++ - 从 Qt C++ 中的另一个应用程序获取文本字段的值

c++ - 在 C++ 中将字符串和列表添加到映射

c++ - 这个 MSVC++ 编译错误是什么意思

c++ - 输入特征样式来测试 T 是否是 basic_string<> 或可打印的类似字符串类型?

c++ - 如何更改 MFC 中的 VIEW 大小以适合输入图像?

c++ - 将字符打印为字母而不将它们转换为数值?

c++ - 使用RAII填充成员对象图并使用智能指针存储一个成员的正确方法

c++ - 静态断言失败 : variant must have no reference alternative

c++ - 通用 find_if 检查二维数组中的元素

c++ - 为什么 injected-class-name 有时不被视为类模板中的模板名称?