fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <utility>
  4. #include <vector>
  5.  
  6. namespace {
  7.  
  8. template <typename T>
  9. class MyAllocator {
  10. public:
  11. using value_type = T;
  12.  
  13. MyAllocator(std::string iType) : _type(std::move(iType)) {}
  14.  
  15. T* allocate(const std::size_t iNo) { return new T[iNo]; }
  16. void deallocate(T* iPtr, const std::size_t) { delete[] iPtr; }
  17.  
  18. constexpr bool operator!=(const MyAllocator& oth) const {
  19. return _type != oth._type;
  20. }
  21.  
  22. const std::string& getType() const noexcept { return _type; }
  23.  
  24. private:
  25. std::string _type;
  26. };
  27.  
  28. using MyString =
  29. std::basic_string<char, std::char_traits<char>, MyAllocator<char>>;
  30.  
  31. } // anonymous namespace
  32.  
  33. int main(int, char**) {
  34. ::MyString str1(::MyAllocator<char>("ForStr1"));
  35. ::MyString str2(::MyAllocator<char>("ForStr2"));
  36. ::MyString str3(::MyAllocator<char>("ForStr3"));
  37.  
  38. std::vector<::MyString> aVector;
  39. aVector.reserve(1024);
  40.  
  41. aVector.push_back(str1);
  42. aVector.push_back(str2);
  43.  
  44. std::cout << "[0]: " << aVector[0].get_allocator().getType() << "\n"
  45. << "[1]: " << aVector[1].get_allocator().getType() << "\n";
  46.  
  47.  
  48. aVector.insert(aVector.begin(), str3);
  49.  
  50. const auto& type0 = aVector[0].get_allocator().getType();
  51. const auto& type1 = aVector[1].get_allocator().getType();
  52. const auto& type2 = aVector[2].get_allocator().getType();
  53.  
  54. std::cout << "[0]: " << type0 << "\n"
  55. << "[1]: " << type1 << "\n"
  56. << "[2]: " << type2 << "\n";
  57.  
  58. return 0;
  59. }
  60.  
Success #stdin #stdout 0s 4248KB
stdin
Standard input is empty
stdout
[0]: ForStr1
[1]: ForStr2
[0]: ForStr1
[1]: ForStr2
[2]: ForStr2