4. Set

4. Set#

Please complete the program while keeping interfaces and implementations seperated.

The program implements a class called Set, which can store any number of std::string objects, and satisfies the following invariants,

  • std::string* data_

    • The member that holds all std::string objects.

  • int size_

    • The member that indicates the amount of std::string objects; if no object exists, size_ == 0.

  • Element uniqueness

    • For any two different objects string1 and string2 holded by data_, string1 == string2 (equality) should not be true.

    • Also, when inserting a new object, the insertion should not happen if there's already an equal object.

You should implement the following functions for it,

  • Constructor Set(std::string* data, int size)

    • Insert all elements inside [data, data + size) into data_.

  • Copy constructor

  • Copy assignment

  • auto operator+=(Set const& other) -> Set&

    • Insert all elements inside other into *this.

  • friend auto operator+(Set const& lhs, Set const& rhs) -> Set

    • Merge two Set as a Set.

  • friend auto operator<<(std::ostream& ostream, Set const& set) -> std::ostream&

    • Output the stored std::string objects with the format [element_1, element_2, ..., element_n].

The following has given part of the Set's implementation and the main() function.

set.hpp#
 1#ifndef SET_HPP
 2#define SET_HPP
 3
 4#include <iosfwd>
 5#include <string>
 6/* you can include any standard headers here */
 7
 8class Set {
 9 public:
10  /* please complete the code */
11
12 private:
13  std::string* data_;
14  int size_;
15};
16
17#endif
main.cpp#
 1#include "set.hpp"
 2
 3#include <iostream>
 4#include <string>
 5
 6auto main() -> int {
 7  std::string s1[] = {"John", "Bat-man", "Doctor", "John"};
 8  std::string s2[] = {"Doctor", "Smith", "Komeji", "Smith"};
 9  std::string s3[] = {"Komeji", "Satori", "Momo", "Satori"};
10
11  Set set1(s1, 4);
12  Set set2(s2, 4);
13  Set set3;
14
15  std::cout << set1 << '\n';
16  std::cout << set2 << '\n';
17  std::cout << set3 << '\n';
18
19  set3  = set2;
20  set1 += set2;
21  set1  = set1 + set3;
22
23  std::cout << set1 << '\n';
24  std::cout << set2 << '\n';
25  std::cout << set3 << '\n';
26}