繁体   English   中英

检查std :: vector中的项目 <std::vector<std::string> &gt;使用std :: find

[英]Checking for Item in std::vector<std::vector<std::string>> Using std::find

我有以下对象

std::vector<std::vector<std::string>> vectorList;

然后我使用添加

std::vector<std::string> vec_tmp;
vec_tmp.push_back(strDRG);
vec_tmp.push_back(strLab);
if (std::find(vectorList.begin(), vectorList.end(), vec_tmp) == vectorList.end())
    vectorList.push_back(vec_tmp);

包含在vectorList中的std::vector<std::string>仅是二维的,没有重复项。 这很好用,但是我现在只想检查vectorList包含索引为零的项目,该索引等于当前的strDrg 在C#中,我什至不会考虑这一点,但是使用C ++似乎并不直接。 如何找到vectorList.at(i)[0]已经存在vectorListstrDrg存在矢量?

注意:我可以使用boost。

find_if与lambda一起使用:

std::find_if(vectorList.begin(), vectorList.end(), 
  [&strDrg](const std::vector<std::string>& v) { return v[0] == strDrg; });

看来您不需要vector的全部力量来满足您的内部元素。 考虑使用:

std::vector<std::array<std::string, 2>>

代替。

为了完全按照您的要求进行操作,最好在std::find_if使用@chris在注释中建议的lambda:

std::find_if(ob.begin(), ob.end(),
    [&](const auto x){return x[0] == strDRG;});
// Replace auto with "decltype(ob[0])&" until
//you have a C++1y compiler. Might need some years.

但是,如果只有两个元素,请考虑使用std::array<...>std::pair<...>std::tuple<...>而不是内部向量。

对于元组和配对,您需要以不同的方式访问第一个元素:

对:成员first
元组:使用get<0>(x);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM