我有以下目标
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);
std::vector<std::string>
所包含的vectorList
仅是二维的,没有重复的.这很好,但我现在只想检查vectorList
是否包含索引为零的项,该项等于当前的strDrg
。在C#中,我甚至不会考虑到这一点,但使用C++似乎并不直接。如何找到vectorList
中是否存在一个向量,其中strDrg
已经存在于vectorList.at(i)[0]
中
注意:我可以使用助推。
发布于 2014-07-22 15:39:38
将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>>
而不是。
发布于 2014-07-22 15:44:47
对于完全按照您的要求进行的操作,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);
https://stackoverflow.com/questions/24891666
复制相似问题