如何在二维向量中找到结构元素? [英] How to find an struct element in a two dimention vector?

查看:84
本文介绍了如何在二维向量中找到结构元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个结构:

struct node
{
    string val;
    int count;
};

我以这种方式定义了向量:

I have defined my vector in this way:

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]

... In this example I have only one dimension in my outer vector so as you can see it is: 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");

但是它没有用.感谢任何建议.

But it did not work. Appreciate any suggestion.

编辑

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

I have defined my own search:

  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"));

但是无法使其正常工作.

But can't make it work.

推荐答案

您需要更改find_if的比较器函子.

You need to change the comparer functor of the 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版本,如下所示:

And use the find_if version like this:

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()允许您访问内部向量的元素和参数receive是内部向量node中元素存储的类型.

The comparer functor of the find_if receive as parameter in the operator() an element of the container to find in. In this case twoD[0].begin() and twoD[0].end() give you access to the elements of the inner vector and the parameters receive is the type of the element storage in the inner vector node.

这篇关于如何在二维向量中找到结构元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆