You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在std::vector<std::vector<ExchangeStruct1>>中搜索指定ID值

二维vector嵌套ID搜索实现方案

你当前使用的代码存在三处问题,因此无法匹配第二层级数据:

  • 存在语法笔误:lambda参数定义多写了一个右尖括号>,会直接编译报错
  • exchangeList是二维vector,外层元素类型为std::vector<ExchangeStruct1>,你直接在第一层find_if的lambda中传入ExchangeStruct1类型的参数,类型不匹配
  • 每个ExchangeStruct1内部的id本身是vector类型,需要根据你的匹配规则(匹配单个ID值/匹配完整ID数组)调整判断逻辑

实现代码

场景1:仅判断指定ID是否存在

如果你的搜索目标key是单个int16_t类型的ID值,可直接用两层遍历实现:

#include <algorithm>

bool checkIdExists(int16_t key, const std::vector<std::vector<ExchangeStruct1>>& exchangeList) {
    // 遍历外层vector的每一个内层vector
    for (const auto& innerVector : exchangeList) {
        // 遍历内层vector的每一个ExchangeStruct1实例
        for (const auto& exchangeObj : innerVector) {
            // 在当前实例的id数组中查找目标值
            if (std::find(exchangeObj.id.begin(), exchangeObj.id.end(), key) != exchangeObj.id.end()) {
                return true;
            }
        }
    }
    return false;
}

如果你的key是std::vector<int16_t>类型,需要和ExchangeStruct1的id数组完全匹配,简化判断逻辑即可:

bool checkIdVecExists(const std::vector<int16_t>& key, const std::vector<std::vector<ExchangeStruct1>>& exchangeList) {
    for (const auto& innerVector : exchangeList) {
        for (const auto& exchangeObj : innerVector) {
            if (exchangeObj.id == key) {
                return true;
            }
        }
    }
    return false;
}

场景2:需要定位到匹配ID的具体对象

如果需要获取匹配ID对应的ExchangeStruct1实例的迭代器,可按以下方式实现:

// 入参key为单个int16_t,返回的pair分别是外层vector迭代器、内层vector迭代器
auto findIdPosition(int16_t key, std::vector<std::vector<ExchangeStruct1>>& exchangeList) 
-> std::pair<decltype(exchangeList)::iterator, decltype(exchangeList[0])::iterator> {
    for (auto outerIt = exchangeList.begin(); outerIt != exchangeList.end(); ++outerIt) {
        auto innerIt = std::find_if(outerIt->begin(), outerIt->end(), [key](const ExchangeStruct1& obj) {
            return std::find(obj.id.begin(), obj.id.end(), key) != obj.id.end();
        });
        if (innerIt != outerIt->end()) {
            return {outerIt, innerIt};
        }
    }
    return {exchangeList.end(), {}};
}

// 调用示例(C++17及以上支持结构化绑定)
auto [outerPos, innerPos] = findIdPosition(1001, exchangeList);
if (outerPos != exchangeList.end()) {
    // 找到匹配对象,innerPos指向对应的ExchangeStruct1实例
}

优化建议

如果数据量较大、查找操作频繁,建议提前构建ID到对象位置的哈希映射表,后续查找复杂度可从O(n²)降到O(1),提升性能。


内容的提问来源于stack exchange,提问作者Marcus Kammarfelt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 18:45:03