Advertisement
Guest User

Untitled

a guest
Mar 21st, 2018
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. //Example class
  2. #include <iostream>
  3. #include <vector>
  4. #include <string>
  5. using namespace std;
  6. class Example {
  7. public:
  8.     Example()
  9.     :i{1}, names{vector<string>{"Whatever"}}{
  10.         //empty body
  11.     }
  12.     explicit Example(int x)
  13.     : i{x},  names{vector<string>{"Whatever"}}{
  14.         if(i < 0){
  15.             i = 0;
  16.         }
  17.     }
  18.     Example(int x, const vector<string>& s)
  19.     : i{x}, names{s}{
  20.         if(i < 0){
  21.             i = 0;
  22.         }
  23.         if(names.size() < 1){
  24.             names.push_back("Whatever");
  25.         }
  26.     }
  27.     void print(){
  28.         cout << "i: " << i << "names size: " << names.size() << endl;
  29.     }
  30.     string getName(size_t position)const {
  31.         string result{};
  32.         if(position < names.size() && position >= 0){
  33.             result = names[position];
  34.         }
  35.         return result;
  36.     }
  37.     void addName(const string& name){
  38.         if(name.size() > 0){
  39.            names.push_back(name);
  40.         }
  41.     }
  42.     void replace(size_t position, const string& name){
  43.         if(position < names.size()){
  44.             names[position] = name;
  45.         }
  46.     }
  47.     size_t count() const{
  48.         return names.size();
  49.     }
  50.  
  51. private:
  52.     int i{};
  53.     vector<string> names{};
  54.     };
  55.     void printAll(const vector<Example>& list){
  56.         for(const Example& f : list){
  57.             for(size_t i{0}; i < f.count();  i += 1){
  58.                 cout << f.getName(i) << endl;
  59.             }
  60.         }
  61.     }
  62.     void testExample(){
  63.         Example a{};
  64.         Example b{3};
  65.         Example c{5, vector<string>{"abc", "def"}};
  66.         a.print();
  67.         b.print();
  68.         c.print();
  69.         vector<Example> ve1{a,b,c};
  70.         vector<Example> ve2{Example{}, Example{1}, Example{2, vector<string>{"a","b","c"}}};
  71.         cout <<"===================" << endl;
  72.         ve2[2].replace(0, "betty");
  73.         for(Example e: ve2){
  74.             cout << e.getName(0) << ' ';
  75.             e.print();
  76.         }
  77.         printAll(ve2);
  78.     }
  79. int main()
  80. {
  81.     testExample();
  82.     cout << "Hello world!" << endl;
  83.     return 0;
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement