So I wrote a Vector
class but there's this linker error that I don't know how to fix:
Undefined symbols for architecture x86_64:
"operator<<(std::__1::basic_ostream<char, std::__1::char_traits<char> >&, Vector<int> const&)", referenced from:
_main in main-be9b4b.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here's the code:
template<typename T>
class Vector {
public:
Vector () {
capacity = 1;
data = alloc(capacity);
size = 0;
}
Vector (size_t cap) : capacity(cap) {
data = alloc(capacity);
size = 0;
}
Vector (const Vector<T>& other) {
capacity = other.capacity;
size = other.size;
data = alloc(capacity);
for (size_t i = 0; i < size; ++i) {
data[i] = other.data[i];
}
}
Vector (Vector<T>&& other) {
capacity = other.capacity;
size = other.size;
data = other.data;
other.capacity = 0;
other.size = 0;
other.data = nullptr;
}
Vector& operator=(const Vector<T>& other) {
Vector<T> tmp(other);
swap(*this, tmp);
return *this;
}
void push_back(T element) {
ensure_space();
data[size++] = element;
}
template<typename... Args>
void emplace_back(Args&... args) {
push_back(T(std::forward<Args>(args)...));
}
friend void swap(Vector<T>& v1, Vector<T>& v2);
friend std::ostream& operator<<(std::ostream& out, const Vector<T>& v);
private:
T* data;
size_t capacity;
size_t size;
T* alloc(size_t cap) {
return new T[cap];
}
void ensure_space() {
if (size < capacity) return;
T* tmp = alloc(capacity << 1);
memcpy(tmp, data, size);
delete[] data;
data = tmp;
capacity <<= 1;
}
};
template<typename T>
void swap(Vector<T>& v1, Vector<T>& v2) {
std::swap(v1.data, v2.data);
std::swap(v1.capacity, v2.capacity);
std::swap(v1.size, v2.size);
}
template<typename T>
std::ostream& operator<<(std::ostream& out, const Vector<T>& v) {
for (size_t i = 0; i < v.size; ++i) {
out << v.data[i] << " ";
}
out << std::endl;
return out;
}