// Eine sehr einfache Vektor-Klasse für die Anwendung in AVRs,
// moderner GCC-Compiler vorausgesetzt (der "auto" und das Bereichs-for-Konstrukt kennt)
// Speicherverwaltung per malloc,realloc und free statt new/delete erspart memcpy
// Der eigentliche Ressourcenfresser ist die dynamische Speicherverwaltung.
template<class T> class vector{
int len;
T*data;
void realloc(int n) {data=(T*)::realloc(data,(len=n)*sizeof(T));}
public:
vector<T>():len(0),data(0) {} // Default-Konstruktor: Erzeugt leeren Vektor
vector<T>(int n) {data=(T*)::malloc((len=n)*sizeof(T));} // Konstruktor mit Platzvorgabe
~vector<T>() {::free(data);} // Destruktor
int size() const {return len;}
const T*begin() const {return data;} // nötig für "for(auto a:b)"
const T*end() const {return data+len;} // nötig für "for(auto a:b)"
void push_back(const T&v) {realloc(len+1);data[len-1]=v;} // Element anfügen
const T&operator[](int i) const {return data[i];} // Elementzugriff rechtsseitig (lesend)
T&operator[](int i) {return data[i];} // Elementzugriff linksseitig (schreibend)
};
// Beispiel-Anwendung:
vector<int> v;
void setup(){
v.push_back(42);
}
void loop(){
for(auto i:v) printf("%d",i); // C++17 (g++-Kommandozeilenschalter -std=C++17)
for(const int*i=v.begin();i<v.end();i++) printf("%d",*i); // früheres C++: Dasselbe bloß umständlicher formuliert
for(int i=0;i<v.size();i++) printf("%d",v[i]); // früheres C++: via Laufindex
}
| Vorgefundene Kodierung: UTF-8 | 0
|