I'm just trying to get C++ down and to do that, I gotta make my own libraries and whatnot. So I'm trying to get the beginnings of my own List template class, exactly like the List class in the JDK. So I've got the template and stuff down, I just wanna know how I would make it so that I could loop through the contents of a list object. This way I can print out the contents of said object. I don't exactly know where to start.
#pragma once
template<typename T> class List {
public:
List() : _size(0), _elements(nullptr) {}
~List() {
if (_elements != nullptr) {
delete[] _elements;
}
}
inline int size() { return _size; }
inline void add(T element) {
_size++;
T* buffer = new T[_size];
if (_elements != nullptr) {
memcpy(buffer, _elements, sizeof(T) * (_size - 1));
delete[] _elements;
}
buffer[_size - 1] = element;
_elements = buffer;
}
inline void remove(T element) {
_size--;
T* buffer = new T[_size];
if (_elements != nullptr) {
memcpy(buffer, _elements, sizeof(T) * _size);
delete[] _elements;
}
else {
assert(false);
}
_elements = buffer;
}
inline T* getElements() {
return _elements;
}
private:
int _size;
T* _elements;
};
And this is my main Cpp file
#include <cstdio>
#include <string>
#include "List.h"
using namespace std;
int main( int argc, char ** argv )
{
string str = "This is a test!";
List<char> list = breakString(str);
for (char c : list.getElements()) {
}
getchar();
return 0;
}
List<char> breakString(string str) {
List<char> list;
for (char c : str) {
list.add(c);
}
return list;
}
So what I'm trying to figure out is in that for loop, I'm used to it being an enhanced for loop like in Java, and is that the same here in C++? If so, how would I make this object iterable?
I figured I would get a more accurate answer to my question if I asked directly.