add a TemplateVector program

this is a Vector using templates which means you can use any type with
the Vector instead of just a double.
This commit is contained in:
Fries 2023-06-23 00:26:42 -07:00
parent eb6fa7a104
commit 95df0a0321
2 changed files with 72 additions and 0 deletions

View file

@ -16,3 +16,4 @@ add_executable(HeapMemory HeapMemory.cc)
add_executable(AbstractClasses AbstractClasses.cc)
add_executable(vector vector.cc)
add_executable(Vector2 Vector2.cc)
add_executable(TemplateVector TemplateVector.cc)

71
src/TemplateVector.cc Normal file
View file

@ -0,0 +1,71 @@
#include <cstdlib>
#include <format>
#include <iostream>
#include <stdexcept>
template <typename T>
class Vector {
private:
T* elem;
int sz;
public:
explicit Vector(int size)
{
elem = new T[size];
sz = size;
}
~Vector()
{
delete[] elem;
}
T& operator[](int i)
{
if (i < 0 || size() <= i) {
#if __cpp_exceptions == 199711
throw std::out_of_range { "Vector::operator[]" };
#else
std::exit(1);
#endif
}
return elem[i];
}
T* begin()
{
return &elem[0];
}
T* end()
{
return &elem[0] + size();
}
constexpr int size() const
{
return sz;
}
};
int main()
{
Vector<double> doubles(5);
Vector<std::string> strings(5);
for (int i = 0; i < doubles.size(); i++) {
doubles[i] = i + 1;
}
for (int i = 0; i < strings.size(); i++) {
strings[i] = std::format("this is element {}", i);
}
for (double i : doubles) {
std::cout << i << std::endl;
}
for (std::string i : strings) {
std::cout << i << std::endl;
}
}