2014-09-08 3 views
0

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.

+0

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? –

+0

@IgorTandetnik C'est ma question. Dans ce cas, que devrions-nous faire? – Bernard

+0

Pourquoi voulez-vous un comparateur qui se prend comme paramètre? Vous voulez comparer une chaîne à un 'node', non? –

Répondre

2

Vous devez modifier le foncteur de la coupure du 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 

et utiliser la version find_if comme ceci:

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

Le foncteur comparateur de find_if reçoivent en tant que paramètre dans le operator() un élément du conteneur à trouver dans Dans ce cas twoD[0].begin() et twoD[0].end() donner. vous accédez aux éléments du vecteur interne et les paramètres reçoivent le type de l'élément de stockage dans le vecteur interne node.

Questions connexes