Skip to content

Instantly share code, notes, and snippets.

@ibrahim5253
Created February 25, 2021 04:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ibrahim5253/860a0fffd4d90e330748ad3c57ba8509 to your computer and use it in GitHub Desktop.
Save ibrahim5253/860a0fffd4d90e330748ad3c57ba8509 to your computer and use it in GitHub Desktop.
`std::vector<T&>`; because, why not?
#include <iostream>
#include <vector>
namespace std {
template<class T>
class vector<T&> {
public:
vector() : data(new T*[capacity]) {}
size_t size() const {
return d_size;
}
void push_back(T& x) {
if (d_size == capacity) {
capacity <<= 1;
T** old_data = data;
data = new T*[capacity];
for (size_t i = 0; i < d_size; ++i)
data[i] = old_data[i];
delete [] old_data;
}
data[d_size] = &x;
++d_size;
}
T& operator[](size_t i) {
return *data[i];
}
const T& operator[](size_t i) const {
return *data[i];
}
~vector() {
delete [] data;
}
private:
size_t d_size = 0;
size_t capacity = 2;
T** data;
};
}
int main()
{
std::vector<int&> v;
int a = 10;
for (auto i = 0; i < 10000; ++i)
v.push_back(a);
v[10] = 100;
std::cout << v.size() << '\n';
std::cout << v[0] << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment