Question #58335

Take the following interfaces for an article respectively a shop selling articles:
class Article // an article
{
public:
virtual Identifier getId() = 0; // its identifier
};
class Shop // a shop
{
public:
// number n of articles in shop
virtual int numberOfArticles() = 0;
// get article i, 0 <= i < n
virtual Article* getArticle(int i) = 0;
};
Write a method
set<Identifier> getArticleIds(Shop& s);
which takes a shop s as parameter and returns as its result the set of the identifiers of all
articles contained in s.

Expert's answer

class Article // an article
{
public:
    virtual Identifier getId() = 0; // its identifier
};
class Shop // a shop
{
public: // number n of articles in shop
    virtual int numberOfArticles() = 0;
    // get article i, 0 <= i < n
    virtual Article* getArticle(int i) = 0;
};
set<Identifier> getArticleIds(Shop& s)
{
    set<Identifier> elements;
    for(int i = 0; i < s.numberOfArticles(); i++)
        elements.insert(s.getArticle(i)->getId());
    return elements;
}
};
Write a method
set<Identifier> getArticleIds(Shop& s);
which takes a shop s as parameter and returns as its result the set of the identifiers of all articles contained in s.
LATEST TUTORIALS
APPROVED BY CLIENTS