turbolist cpp implementation - first version and seems to be working

This commit is contained in:
masterexplorer 2024-08-27 10:13:29 +02:00
parent 59826852e4
commit b61da10f35
2 changed files with 53 additions and 3 deletions

View File

@ -4,8 +4,21 @@
#include<cstdint>
#include"turbolist.h"
#define PRINT_DBG 1
int main() {
TurboList list(4);
for(int i = 0; i < 65535; ++i) {
list.insert(i);
}
#ifdef PRINT_DBG
for(int i = 0; i < 65535; ++i) {
printf("%d\n", list[i]);
}
#endif /* PRINT_DBG */
printf("sizeof(int)> %d\n", sizeof(int));
return 0;
}

View File

@ -1,5 +1,9 @@
#ifndef TURBO_LIST_H
#define TURBO_LIST_H
#include<cstdint>
#include<cstdlib>
#include<cassert>
class TurboList {
int *old;
@ -11,18 +15,51 @@ class TurboList {
uint32_t capacity;
uint32_t count;
public:
inline TurboList(uint32_t cap) noexcept :
inline TurboList(uint32_t initial_cap = 16) noexcept :
old(nullptr),
mid(0),
end(0),
capacity(cap),
capacity(initial_cap),
count(0) {
nex = (int*) malloc(this->capacity * sizeof(uint32_t));
nex = (int *) malloc(this->capacity * sizeof(int));
}
inline ~TurboList() noexcept {
if(nex) free(nex);
if(old) free(old);
}
inline int& operator[](uint32_t i) noexcept {
if(i < mid) {
return old[i];
} else {
return nex[i];
}
}
inline void insert(int elem) noexcept {
if(count < capacity) {
// INSERT
if(mid > 0) {
nex[mid - 1] = old[mid - 1];
--mid;
}
nex[end++] = elem;
++count;
} else {
// GROW
assert(mid == 0);
if(old) free(old);
old = nex;
mid = end;
capacity *= 2;
nex = (int *) malloc(this->capacity * sizeof(int));
// Will go into the INSERT code path here
insert(elem);
}
}
};
#endif /* TURBO_LIST_H */