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:
parent
eb6fa7a104
commit
95df0a0321
2 changed files with 72 additions and 0 deletions
|
@ -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
71
src/TemplateVector.cc
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue