J'ai un struct:Comment trouver un élément struct dans un vecteur à deux dimensions?
struct node
{
string val;
int count;
};
J'ai défini mon vecteur de cette façon:
typedef std::vector<node> StringVector;
typedef std::vector<StringVector> StringVector2D;
Et voici mon 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;
}
... Dans cet exemple, avoir une seule dimension dans mon vecteur externe de sorte que vous pouvez le voir est: twoD[0]
StringVector::iterator it = find(twoD[0].begin(), twoD[0].end(), "ben");
if(it == twoD[0].end())
{
cout<<"not found"<<endl;
}
J'ai utilisé cette
StringVector::iterator it = find(twoD[0].begin().val, twoD[0].end().val, "ben");
et
StringVector::iterator it = find(twoD[0].begin()->val, twoD[0].end()->val, "ben");
Mais cela n'a pas fonctionné. Appréciez toute suggestion.
EDIT
J'ai défini ma recherche:
struct find_word
{
string val;
find_word(string val) : val(val) {}
bool operator() (const find_word& m) const
{
return m.val == val;
}
};
Et appelez ici:
StringVector::iterator it = find_if(twoD[0].begin()->val, twoD[0].end()->val, find_word("ben"));
mais ne peut pas le faire fonctionner.
Les éléments de 'twoD [0]' sont 'node's. Vous recherchez une chaîne. Qu'est-ce que cela signifie pour un 'node' de correspondre à une chaîne? Comment le compilateur est censé savoir cela? –
@IgorTandetnik C'est ma question. Dans ce cas, que devrions-nous faire? – Bernard
Pourquoi voulez-vous un comparateur qui se prend comme paramètre? Vous voulez comparer une chaîne à un 'node', non? –