如何在二维向量中找到struct元素?

时间:2014-09-08 14:25:21

标签: c++ search vector stl find

我有一个结构:

struct node
{
    string val;
    int count;
};

我已经用这种方式定义了我的矢量:

typedef std::vector<node> StringVector;
typedef std::vector<StringVector> StringVector2D;

这是我的代码:

string arr[6] = {"hi","mr","ben","ss","rty","ben"};

StringVector2D twoD;    

StringVector inner;
twoD.push_back(inner);  


for(int f=0;f<6;f++)
{

    node tmp;
    tmp.val = arr[f];
    tmp.count = arr[f].size();

    twoD[0].push_back(tmp); 

}


for (StringVector::iterator it = twoD[0].begin() ; it != twoD[0].end(); ++it)
{
    cout<< it->val<<endl;
}

...在这个示例中,我的外部向量中只有一个维度,因此您可以看到它:twoD[0]

StringVector::iterator it = find(twoD[0].begin(), twoD[0].end(), "ben");

if(it == twoD[0].end())
{
    cout<<"not found"<<endl;
}

我用过这个

StringVector::iterator it = find(twoD[0].begin().val, twoD[0].end().val, "ben");

StringVector::iterator it = find(twoD[0].begin()->val, twoD[0].end()->val, "ben");

但它没有用。感谢任何建议。

修改

我已经定义了自己的搜索:

  struct find_word
    {
        string val;
        find_word(string val) : val(val) {}
        bool operator () ( const find_word& m ) const
        {
            return m.val == val;
        }
};

并在此处致电:

StringVector::iterator it = find_if(twoD[0].begin()->val, twoD[0].end()->val, find_word("ben"));

但无法使其发挥作用。

1 个答案:

答案 0 :(得分:2)

您需要更改find_if的比较器仿函数。

struct find_word {
    string val;
    find_word(string val) 
      : val(val) {}
    bool operator()(const node& m) const { return m.val == val; }
}; //                     ^^^^ the change is here 

并使用find_if这样的版本:

StringVector::iterator it = find_if(twoD[0].begin(), twoD[0].end(), find_word("ben"));
//                              the change is here ^     and here ^

find_if的比较器仿函数作为参数在operator()要查找的容器元素中接收。在这种情况下,twoD[0].begin()twoD[0].end()可让您访问内部向量和参数接收的元素是内部向量node中元素存储的类型。