Exercise: Bag Of Items, By Copy

Step 1: Insert, Find

Write a class BagCopy that

  • contains objects of a nested Item class by copy

  • uses a std::vector internally

The class supports the methods

  • insert()

  • find_by_int() const (try to use range based for in the implementation)

Make the following tests pass:

#include "bag-copy.h"

#include <gtest/gtest.h>


TEST(bag_copy_suite, find_by_int_ok)
{
    BagCopy bag;
    bag.insert(BagCopy::Item("something", 42));
    bag.insert(BagCopy::Item("anything", 666));

    auto item = bag.find_by_int(42);
    ASSERT_EQ(item.first, "something");
    ASSERT_EQ(item.second, 42);
}

TEST(bag_copy_suite, find_by_int_nok)
{
    BagCopy bag;
    bag.insert(BagCopy::Item("something", 42));
    bag.insert(BagCopy::Item("anything", 666));

    BagCopy::Item item = bag.find_by_int(7);
    ASSERT_EQ(item.first, "");
    ASSERT_EQ(item.second, 0);
}

Step 2: Remove

Implement a remove_by_int() method such that the following test passes. Read careful how the return value of the erase() method of std::vector is used to modify a container while iterating over it.

Make the following test pass:

#include "bag-copy.h"

#include <gtest/gtest.h>


TEST(bag_copy_suite, remove_by_int_ok)
{
    BagCopy bag;
    bag.insert(BagCopy::Item("something", 42));
    bag.insert(BagCopy::Item("anything", 666));

    std::size_t nremoved = bag.remove_by_int(42);
    ASSERT_EQ(nremoved, 1);
}