The Go programming language has that slice type, which is under the hood a pointer to an actual array. This allows treating the subarrays as actual arrays with almost no performance overhead. This code snippet is about implementing slice type for C++ arrays and vectors.
slice.h:
#ifndef SLICE_H
#define SLICE_H
#include <sstream>
#include <stdexcept>
#include <string>
template<class T>
class slice {
private:
T* m_array;
size_t m_length;
public:
slice(T* array, size_t length) {
this->m_array = array;
this->m_length = length;
}
slice(T* array, size_t length, size_t skip) {
this->m_array = array + skip;
this->m_length = length;
}
T& operator[](size_t index) {
if (index >= m_length) {
std::ostringstream os;
os << "Bad index: " << index << ", slice size: " << m_length;
throw std::runtime_error(os.str());
}
return m_array[index];
}
size_t size() {
return m_length;
}
T* begin() {
return m_array;
}
T* end() {
return m_array + m_length;
}
const T* begin() const {
return m_array;
}
const T* end() const {
return m_array + m_length;
}
};
#endif /* SLICE_H */
main.cpp:
#include <algorithm>
#include <iostream>
#include <vector>
#include "slice.h"
using std::cout;
using std::endl;
using std::vector;
int main(int argc, char** argv) {
int int_array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
//// Should be 4, 5, 6, 7, 8.
slice<int> pizza_slice = slice<int>(int_array, 5, 3);
cout << "Arrays slice size: " << pizza_slice.size() << endl;
for (int i : pizza_slice)
{
cout << i << endl;
}
vector<int> int_vector = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
//// Should be 2, 3, 4
pizza_slice = slice<int>(&int_vector[0], 3, 1);
cout << "Vector slice size: " << pizza_slice.size() << endl;
for (int i : pizza_slice)
{
cout << i << endl;
}
return 0;
}
Any critique is much appreciated.
operator[] const
; and don't you need to copy the slice if the user tries to modify it? Otherwise you end up modifying the original array as well as the slice. Right now all you've got is a slightly heavier-weight version ofT*
. \$\endgroup\$append(...)
andcopy(...)
functions, your slice is hardly "go like" \$\endgroup\$