Bonjour,
j'ai une classe Element de la sorte :
1 2 3 4 5 6
| class Element
{
public:
std::string m_id;
int m_value
}; |
j'ai un vecteur d'éléments de type Element :
std::vector< Element * > * theVectorOfElements;
j'ai une fonction de recherche d'un élément Element dans le vecteur en fonction de son identifiant :
Element * searchElement( std::string anId , std::vector< Element * > * aVectorOfElements );
sachant que :
- tous les attributs m_id des différents éléments du vecteur sont distincts
- lorsque je fais une recherche pour anId, je suis sûr qu'il existe bien un élément du vecteur qui à comme attribut m_id cet valeur anId (ce qui suppose en plus que ce vecteur n'est pas vide.
j'ai donc implémenté cette fonction de la manière suivante :
1 2 3 4 5 6 7 8 9 10 11
| Element * searchElement( std::string anId , std::vector< Element * > * aVectorOfElements )
{
std::vector< Element * >::iterator anIter = aVectorOfElements->begin();
for( ; anIter != aVectorOfElements->end() ; ++anIter )
{
if( (*anIter)->m_id == anId )
{
return( (*anIter) );
}
}
} |
Or j'ai un warning à la compilation :
"warning: control reaches end of non-void function"
dû au fait que le "return" est dans la boucle.
Comme ce vecteur est très grand et selon mes hypothèses, je préfère ne pas avoir à le parcourir en entier si pas besoin. Comment puis-je faire pour éviter ce warning ?
Peut-être en faisant une boucle while de la sorte (avec une variable temporaire booléenne) :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| Element * searchElement( std::string anId , std::vector< Element * > * aVectorOfElements )
{
Element * theReturnedElement = NULL;
bool isFind = false;
std::vector< Element * >::iterator anIter = aVectorOfElements->begin();
while( ( false == isFind ) & ( anIter != aVectorOfElements->end() ) )
{
if( (*anIter)->m_id == anId )
{
isFind = true;
theReturnedElement = *anIter;
}
++anIter;
}
return( theReturnedElement );
} |
Mais cela m'oblige à rajouter deux variables internes à la fonction.
Partager