1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
|
#include <vector>
#include <algorithm>
#include <iostream>
#include <initializer_list>
#include <cstdlib>
#include <ctime>
template <typename T>
class container {
size_t size_ {};
T* tainer {};
public:
container() {}
container(size_t s) : tainer(new T[s]), size_(s) {}
~container() { delete[] tainer; }
container(const container& c) : size_(c.size_), tainer(new T[c.size_]) {
std::copy_n(c.tainer, size_, tainer);
}
container(const std::initializer_list<T>& il) : size_(il.size()), tainer(new T[il.size()]) {
std::copy(il.begin(), il.end(), tainer);
}
container(container&& c) { swap(c); }
container& operator=(const container& c) { auto c1 {c}; swap(c1); return *this; }
container& operator=(container&& c) { swap(c); return *this; }
void swap(container& c) {
std::swap(c.size_, size_);
std::swap(c.tainer, tainer);
}
container(const std::vector<T>& v) : size_(v.size()), tainer(new T[v.size()]) {
std::copy_n(v.begin(), size_, tainer);
}
container(size_t s, const T& val) : size_(s), tainer(new T[s]) {
std::fill_n(tainer, s, val);
}
void shuffle() {
for (auto a {rand() % 100}; a; --a)
std::swap(tainer[rand() % size_], tainer[rand() % size_]);
}
T& operator[](size_t index) { return tainer[index]; }
const T& operator[](size_t index) const { return tainer[index]; }
void push_back(const T& val) {
const auto c {new T[size_ + 1]};
std::copy_n(tainer, size_, c);
c[size_++] = val;
delete[] tainer;
tainer = c;
}
size_t size() const { return size_; }
};
template<typename T>
std::ostream& operator<<(std::ostream& os, const container<T>& c) {
for (size_t i = 0; i < c.size(); ++i)
os << c[i] << ' ';
return os;
}
int main()
{
srand(static_cast<unsigned>(time(nullptr)));
container<int> c {1, 2, 3};
c.push_back(4);
c.push_back(5);
c.push_back(6);
c.shuffle();
std::cout << c << '\n';
const auto c1 {c};
std::cout << c1 << '\n';
container<int> c2;
c2 = container<int> {10, 11, 12};
std::cout << c2 << '\n';
const auto c3 {container<int>{5, 6, 7, 8}};
std::cout << c3 << '\n';
const container c4(10, 34);
std::cout << c4 << '\n';
}
| |