/*************************************************************************** * Copyright (C) 2004 by Michael Schulze * * mike.s@genion.de * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef _containerutils_H_ #define _containerutils_H_ /** * some stuff to find/filter etc through containers */ /** * Returns the Iterator where predicate(*iter) == TRUE */ template Iter find(Iter pos, Iter end, const TUnaryPredicate& predicate) { for (; pos != end; ++pos) { if (predicate(*pos)) { return pos; } } return NULL; } /** * An Iterator over all Elements where the given predicate returned TRUE * For example, to find all Tracks with a given artist/album we need to create * a predicate like this: class AlbumFinder { public: AlbumFinder(const QString& artist, const QString & album) : _artist_(artist.lower()), _album_(album.lower()) {} bool operator () (const TrackMetadata * track) { return _artist_.compare( track->getArtist().lower() ) == 0 && _album_.compare( track->getAlbum().lower() ) == 0; } private: const QString _artist_; const QString _album_; }; ... and use it in the following function TrackList * ITunesDB::getAlbum(const QString &artistname, const QString &albumname) const { kdDebug() << "ITunesDB::getAlbum()" << endl; TrackList * result = new TrackList(); FilteredIterator albumIter(trackmap.begin(), trackmap.end(), AlbumFinder(artistname, albumname)); while (albumIter.hasNext()) { result->addPlaylistItem(*(*albumIter.next())); } return result; } */ template class FilteredIterator { public: FilteredIterator(Iter start, Iter end, TUnaryPredicate predicate) : _pos_(start), _end_(end), _next_(NULL), _unarypredicate_(predicate) {} bool hasNext() { calcNext(); return _next_; } Iter next() { calcNext(); Iter result = _next_; _next_ = NULL; return result; } private: void calcNext() { for ( ; _pos_ != _end_ && _next_ == NULL; ++_pos_) { if (_unarypredicate_(*_pos_)) { _next_ = _pos_; } } } Iter _pos_; Iter _end_; Iter _next_; TUnaryPredicate _unarypredicate_; }; #endif