Hi, how to fix that error in the function begin()? I'm using Visual Studio 2015. Possibly the original source code was made on Linux or CodeBlocks IDE, and possibly it doesn't show that error?
#include "stdafx.h"
#include <vector>
#include <conio.h>
template <typename T>
struct emc_vector {
size_t size() const { return m_data.size(); }
T *begin() {
return &m_data[0]; // <-- "Error: Expression vector subscript out of range" because m_data.size() is 0.
}
T *end() {
if (size()) {
//return &m_data[size()]; [error] Expression vector subscript out of range
return &m_data[size() - 1] + 1;
}
else {
return begin();
}
}
void insert(T *at, const T& value = T()) {
m_data.insert(m_data.begin() + size_t(at - begin()), value);
}
void push_back(const T &value) {
m_data.push_back(value);
}
private:
std::vector<T> m_data;
};
int main()
{
emc_vector<char> vec; // Its size is 0.
//vec.push_back('a');
vec.insert(vec.begin(), 'x'); // <-- This is the goal, but it crashes.
_getch();
return 0;
}