How to find an struct element in a two dimention v

2019-09-16 18:02发布

I have a struct:

struct node
{
    string val;
    int count;
};

I have defined my vector in this way:

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

And here is my code:

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;
}

... 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;
}

I used this

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

and

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

But it did not work. Appreciate any suggestion.

EDIT

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;
        }
};

And call it here:

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

But can't make it work.

1条回答
老娘就宠你
2楼-- · 2019-09-16 18:45

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 

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 ^

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.

查看更多
登录 后发表回答