Why is this giving me an access violation? (C++) - c++

I'm building a vector class for my data structures class, and I can't figure out why this is throwing an exception. Here's the complete Vector.h file:
#include <iostream>
using namespace std;
template <class T>
class Vector {
private:
// not yet implemented
Vector(const Vector& v);
Vector& operator=(const Vector& v);
T * Tarray;
int arraySize;
int currentSize;
public:
Vector() {
arraySize = 2;
currentSize = 0;
Tarray = new T[arraySize];
};
~Vector() {
delete[] Tarray;
};
void push_back(const T &e) {
++currentSize;
if (currentSize > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = new T[arraySize];
for (int j = 0; j < currentSize; j++) {
Tarray[j] = temp[j];
}
delete[] temp;
Tarray[currentSize - 1] = e;
}
else {
Tarray[currentSize - 1] = e;
}
};
void print() {
for (int i = 0; i < currentSize; i++) {
cout << Tarray[i] << " ";
}
};
int getCurrentSize() {
return currentSize;
};
int getArraySize() {
return arraySize;
};
// Not yet implemented
void pop_back();
int size() const;
T& operator[](int n);
};
And here's my complete main.cpp I was using to test it.
#include "Vector.h"
#include <iostream>
#include <string>
using namespace std;
int main() {
char c;
string * temp = new string[8];
Vector<string> newVector;
for (int i = 0; i < 8; i++) {
newVector.push_back("Hello world");
newVector.push_back("Hello world");
}
newVector.print();
cout << endl << "Current Size: " << newVector.getCurrentSize();
cout << endl << "Array Size: " << newVector.getArraySize();
cin >> c;
}

I would rewrite push_back as follows:
void push_back(const T &e) {
if (currentSize+1 > arraySize) {
arraySize *= 4;
T * temp = new T[arraySize];
for (int i = 0; i < currentSize; i++) {
temp[i] = Tarray[i];
}
delete[] Tarray;
Tarray = temp;
}
Tarray[currentSize] = e;
++currentSize;
};
Changes are:
Don't update currentSize until after you have copied the contents (thus not going out of bounds in Tarray).
Don't allocate and copy twice. Just assign Tarray to temp after deleting it.
Only stick element into Tarray in one place.
Update currentSize after, to avoid having to do -1 (It does require a single +1 in the first if instead.

Related

can't figure out where the heap overwriting is

#include<iostream>
using namespace std;
class Text{
public:
~Text(){
delete data;
}
char* data{};
int mSize{};
void fill(char* stringInput) {
mSize = strlen(stringInput);
data = new char [mSize];
for (int i = 0; i < mSize; i++){
data[i] = stringInput[i];
}
}
};
class myString{
public:
explicit myString(int size){ // constructor
strAmount = size;
strings = new Text [size];
}
~myString(){ // destructor
delete[] strings;
}
void addString(char* input){
strings[filledAmount].fill(input);
filledAmount++;
}
void delString(int pos){
for ( int i = pos; i < filledAmount; i++){
swap(strings[i], strings[i+1]);
}
strings[filledAmount].data = nullptr;
strings[filledAmount].mSize = 0;
filledAmount--;
}
void eraseEverything(){
for ( int i = 0; i < filledAmount; i++){
strings[i].data = {};
strings[i].mSize = 0;
}
filledAmount = 0;
}
int maxString() const {
int index{};
for ( int i = 0 ; i < filledAmount; i++){
if (strings[i].mSize > strings[index].mSize){
index = i;
}
}
return index;
}
int charAmount(){
int counter{};
for(int i = 0 ; i < filledAmount; i++){
counter+=strings[i].mSize;
}
return counter;
}
double digitPercentage(){
int digitsAmount{};
for(int i = 0; i < filledAmount; i++){
for ( int j = 0; j < strings[i].mSize; j++){
if (isdigit(strings[i].data[j])){
digitsAmount++;
}
}
}
double digitPercent = (digitsAmount/(double)charAmount())*100;
return digitPercent;
}
int filledAmount{};
int strAmount{};
Text* strings;
};
void render_text(myString& obj) {
for (int k = 0; k < obj.filledAmount; k++) {
for (int i = 0; i < obj.strings[k].mSize; i++)
cout << obj.strings[k].data[i];
cout << endl;
}
cout << endl;
}
int main(){
myString a(5);
a.addString((char *) "zxc 1v1 forever shadow fiend");
a.addString((char *) "This is a string");
a.addString((char *) "12345");
a.addString((char *) "Hello");
a.addString((char *) "A1oha Dance");
render_text(a);
a.delString(1);
render_text(a);
int maxInd = a.maxString();
cout << "Max string :\n";
for (int i = 0; i < a.strings[maxInd].mSize; i++) {
cout << a.strings[maxInd].data[i];
}
cout << "\n\n";
}
Please help me find the crash point. I suppose it crashes in the destructor pole, but I still can't figure it out.
This is something like a self-written string class, the problem is that I can't find the place where the problems start.
I also have a thought that the destructor tries to delete too much memory from the heap so the compiler prevents it from doing that. Can I somehow change the size of the strings array?
I have fixed all your memory errors, with the help of address sanitizers
The main change here is:
Add copy constructors and copy assignment operators
Manually delete the last element in the function delString
Though that the code now works, it's not a true modern c++ style code. I highly recommend that your using std::string to replace your Text class. Use std::vector to replace the dynamic array. Then you will stay away from the pain of memory errors. The delString should be replaced with vector::erase,which is much neat than your hand write algorithm.
https://en.cppreference.com/w/cpp/string/basic_string
https://en.cppreference.com/w/cpp/container/vector
I strongly recommend rewriting the code with std::string and std::vector
#include <cstring>
#include <iostream>
using namespace std;
class Text {
public:
~Text() { delete[] data; }
char* data{};
int mSize{};
Text() = default;
Text(const Text& oth) {
mSize = oth.mSize;
data = new char[mSize];
std::copy(oth.data, oth.data + oth.mSize, data);
}
Text& operator=(const Text& oth) {
delete[] data;
mSize = oth.mSize;
data = new char[mSize];
std::copy(oth.data, oth.data + oth.mSize, data);
return *this;
}
void fill(char* stringInput) {
mSize = strlen(stringInput) + 1;
data = new char[mSize];
for (int i = 0; i < mSize; i++) {
data[i] = stringInput[i];
}
}
};
class myString {
public:
explicit myString(int size) { // constructor
strAmount = size;
strings = new Text[size];
}
myString(const myString& oth) {
strAmount = oth.strAmount;
strings = new Text[oth.strAmount];
for (size_t i = 0; i < strAmount; ++i) {
strings[i] = oth.strings[i];
}
}
myString& operator=(const myString& oth) {
delete[] strings;
strAmount = oth.strAmount;
strings = new Text[oth.strAmount];
for (size_t i = 0; i < strAmount; ++i) {
strings[i] = oth.strings[i];
}
return *this;
}
~myString() { // destructor
delete[] strings;
}
void addString(char* input) {
strings[filledAmount].fill(input);
filledAmount++;
}
void delString(int pos) {
for (int i = pos; i < filledAmount; i++) {
swap(strings[i], strings[i + 1]);
}
delete[] strings[filledAmount].data;
strings[filledAmount].data = nullptr;
strings[filledAmount].mSize = 0;
filledAmount--;
}
void eraseEverything() {
for (int i = 0; i < filledAmount; i++) {
strings[i].data = {};
strings[i].mSize = 0;
}
filledAmount = 0;
}
int maxString() const {
int index{};
for (int i = 0; i < filledAmount; i++) {
if (strings[i].mSize > strings[index].mSize) {
index = i;
}
}
return index;
}
int charAmount() {
int counter{};
for (int i = 0; i < filledAmount; i++) {
counter += strings[i].mSize;
}
return counter;
}
double digitPercentage() {
int digitsAmount{};
for (int i = 0; i < filledAmount; i++) {
for (int j = 0; j < strings[i].mSize; j++) {
if (isdigit(strings[i].data[j])) {
digitsAmount++;
}
}
}
double digitPercent = (digitsAmount / (double)charAmount()) * 100;
return digitPercent;
}
int filledAmount{};
int strAmount{};
Text* strings = nullptr;
};
void render_text(myString& obj) {
for (int k = 0; k < obj.filledAmount; k++) {
for (int i = 0; i < obj.strings[k].mSize; i++)
cout << obj.strings[k].data[i];
cout << endl;
}
cout << endl;
}
int main() {
myString a(6);
a.addString((char*)"zxc 1v1 forever shadow fiend");
a.addString((char*)"This is a string");
a.addString((char*)"12345");
a.addString((char*)"Hello");
a.addString((char*)"A1oha Dance");
render_text(a);
a.delString(1);
render_text(a);
int maxInd = a.maxString();
cout << "Max string :\n";
for (int i = 0; i < a.strings[maxInd].mSize; i++) {
cout << a.strings[maxInd].data[i];
}
cout << "\n\n";
return 0;
}

Copying data in a simple vector class

I'm trying write my own vector class:
template <typename T>
class Vector {
public:
Vector(int default_size = 2) :
size(0), data_member(new T[default_size]), capacity(default_size) {};
Vector(const Vector& obj)
{
data_member = new T[obj.size];
data_member = obj.data_member;
size = obj.size;
capacity = obj.capacity;
}
void push_back(T& elem)
{
if (size == capacity)
resize(2 * size);
data_member[size] = elem;
size++;
}
void push_front(T& data)
{
if (size + 1 == capacity)
resize(2 * size);
for (int i = size - 1; i >= 0; i--)
{
data_member[i + 1] = data_member[i];
}
data_member[0] = data;
size++;
}
void pop_back()
{
--size;
}
void resize(int size_)
{
if (size_ > capacity)
{
T* temp = new T[size_];
memcpy(temp, data_member, size * sizeof(T));
delete[] data_member;
data_member = new T[size_];
data_member = temp;
//delete[] temp;
capacity = size_;
}
}
int get_size() { return size; }
T* getarr() { return data_member; }
private:
T* data_member;
int size;
int capacity;
};
and here is a main for testing my class
int main()
{
Vector<int> myint;
int a = 5, b = 8, c = 9;
myint.push_back(a);
myint.push_back(b);
myint.push_back(c);
Vector<int> you = myint;
int* arr1 = you.getarr();
for (int i = 0; i < you.get_size(); i++)
{
cout << *arr1 << endl;
arr1++;
}
cout << endl << endl;
int h[3] = { 1,2,3 };
int* hp = h;
int g[3] = { 4,5,6 };
int* gp = g;
int f[3] = { 4,5,6 };
int* fp = f;
Vector<int*> myarrint;
myarrint.push_back(hp);
myarrint.push_back(gp);
myarrint.push_back(fp);
int** arr = myarrint.getarr();
for (int i = 0; i < myarrint.get_size(); i++)
{
for (int j = 0; j < 3; j++)
{
cout << **arr << endl;
(*arr)++;
}
arr++;
}
cout << endl << endl;
Vector<string> mystr;
string s1 = "I";
string s2 = "went";
string s3 = "shopping";
mystr.push_back(s1);
mystr.push_back(s2);
mystr.push_back(s3);
string* str1 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str1 << endl;
str1++;
}
cout << endl << endl;
string i = "wow";
mystr.push_front(i);
string* str2 = mystr.getarr();
for (int i = 0; i < mystr.get_size(); i++)
{
cout << *str2 << endl;
str2++;
}
cout << endl << endl;
return 0;
}
I'm new in c++ and I'm really confused, I think in my push_back function, I'm just making my objects point to temp and I'm not copying temp in them , so if I want to delete temp in the end of my push_back function my data_members will be lost. So what is the right way to do so?
second if I want to make a dynamic array of strings my program will crash sometimes, and I think ,it's because of memcpy() in my resize function, still I don't know what should I do instead of it?

Code runs when in main() but gives error when in function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am writing a dynamic matrix class that stores each non-zero value as a List of 3 elements [row,column,value]
I made a dynamic array class called "List", and class"Matrix" a List of list pointers.
My code to transpose the Matrix works:
void transpose(Matrix tripleList)
{
for (int i = 0; i < tripleList.getNumOfElem(); i++)
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
cout << "\n";
}
}
it works when written directly in main() but gives error when in stand alone function. can anyone explains why and how to fix it?
Full code:
#include <iostream>
using namespace std;
class List //a dynamic int pointer array
{
private:
int capacity;
int numOfElem;
int *arr;
//initialize all values in capacity to 0
void initialize(int from)
{
for (int i = from; i < capacity; i++)
{
arr[i] = 0;
}
}
//double the capaicty, then initialize
void expand()
{
capacity *= 2;
int *tempArr = new int[capacity];
for (int i = 0; i < numOfElem; i++)
tempArr[i] = arr[i];
delete[] arr;
arr = tempArr;
initialize(numOfElem);
}
public:
List()//constructor
{
capacity = 10;
numOfElem = 0;
arr = new int[capacity];
}
~List()//destrcutor
{
delete[] arr;
}
//add int to the end of List
void append(int newElement)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = newElement;
}
//Copy all element of an input list to the end of List
void copy(List list)
{
for (int i = 0; i < list.getNumOfElem(); i++)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = list.getAt(i);
}
}
//get reference of the int at an index in te list
int* getAddress(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return &arr[index];
}
//change the value of at specific index
void set(int index, int value)
{
arr[index] = value;
}
//get int at an index in te list
int getAt(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return arr[index];
}
int getNumOfElem()
{
return numOfElem;
}
void displayList()
{
for (int i = 0; i < numOfElem; i++)
{
cout << arr[i] << " ";
}
}
};
class Matrix //a List of list pointers
{
private:
int capacity;
int numOfElem;
List* *arr;
void initialize(int from)
{
for (int i = from; i < capacity; i++)
{
arr[i] = new List;
}
}
void expand()
{
capacity *= 2;
List* *tempArr = new List*[capacity];
for (int i = 0; i < numOfElem; i++)
tempArr[i] = arr[i];
delete[] arr;
arr = tempArr;
initialize(numOfElem);
}
public:
Matrix()
{
capacity = 10;
numOfElem = 0;
arr = new List*[capacity];
}
~Matrix()
{
delete[] arr;
}
void append(List* newElement)
{
if (numOfElem >= capacity)
expand();
arr[numOfElem++] = newElement;
}
void set(int index, List* value)
{
arr[index] = value;
}
List* getAt(int index)
{
if (index < 0 || index >= numOfElem)
throw ("Out of bounds exception!!!");
return arr[index];
}
int getNumOfElem()
{
return numOfElem;
}
};
void transpose(Matrix tripleList)
{
for (int i = 0; i < tripleList.getNumOfElem(); i++)
{
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
cout << "\n";
}
}
int main()
{
int m, n, input;
cout << "Please enter the number of rows and columns of the matrix :\n";
cin >> m >> n;
Matrix tripleListMatrix;
int k = 0;
cout << "Please enter the matrix : \n";
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> input;
if (input != 0)
{
tripleListMatrix.append(new List);
(*(tripleListMatrix.getAt(k))).append(i + 1);
(*(tripleListMatrix.getAt(k))).append(j + 1);
(*(tripleListMatrix.getAt(k))).append(input);
k++;
}
}
}
cout << "The triple list of matrix is:\n";
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
(*(tripleListMatrix.getAt(i))).displayList();
cout << "\n";
}
cout << "\n\n";
//transpose(tripleListMatrix);
//the code below is the same as in the function transpose but transpose gives error
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
List* list = new List;
(*list).copy(*(tripleListMatrix.getAt(i)));
int temp = (*list).getAt(0);
(*list).set(0, (*list).getAt(1));
(*list).set(1, temp);
(*list).displayList();
//cout << "\t" << list;
cout << "\n";
}
cout << "\n\n";
//checking that tripleListMatrix is unchanged
for (int i = 0; i < tripleListMatrix.getNumOfElem(); i++)
{
(*(tripleListMatrix.getAt(i))).displayList();
cout << "\n";
}
return 0;
}
List* *arr;
When you call transpose(), it makes a copy Matrix because you're not passing by reference. That copy just has a copy of the address for your List, not it's own List object. When the destructor runs on the copy, it clears up the allocated memory, but the original Matrix object in main still points to that same memory. When that object goes away, its destructor tries to free the same memory again and that's bad.
You probably meant:
void transpose(Matrix const & tripleList)
So that no copy is made when calling transpose(), but you should also explicitly delete the copy construtor of Matrix so it cannot be called
Matrix(Matrix const &) = delete;
or make an explicit Matrix copy constructor that makes a deep copy of the memory.

How to access elements of the array just by having the array's memory location? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So, this is just few methods from my myArray.cpp class. It gives me error on
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
these above code(error - which is non-class type double). can anyone please help me? I'm trying to copy an array to the object array
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
That's my main.cpp class
#include <iostream>
#include "myArray.h"
//#include "myArray.cpp"
using namespace std;
int main (int argc, char **argv)
{
cout << "**************Testing Default Constructor*****************" << endl;
myArray A1;
cout << "A1: ";
A1.print();
cout << "**************Testing Alt Constructor 1*****************" << endl;
myArray A2(5,0);
cout << "A2: ";
A2.print();
cout << "**************Testing init*****************" << endl;
A2.init();
cout << "A2 after init: ";
A2.print();
int size = 5;
double *temp = new double[size];
for(int i = 0; i < size; i++)
{
temp[i] = i;
}
cout << "**************Testing Alt Constructor 2*****************" << endl;
myArray A3(temp, size);
cout << "A3: ";
cout << A3.getSize();
cout << endl;
cout << "Fe";
A3.print();
That's my myArray.cpp class
#ifndef MYARRAY_H_INCLUDED
#define MYARRAY_H_INCLUDED
/***************************************************************************
* myArray class header file
***************************************************************************/
class myArray
{
public:
myArray();
myArray(int,double);
myArray(double*, int);
~myArray();
int getSize() const;
bool equal(const myArray &rhs) const;
void setData(int index, double value);
void insert(int, double);
void remove(int);
double get(int);
void clear();
int find(double);
bool equals(myArray&);
void print() const;
void init();
double getData(int index) const;
// void init();
// void print() const;
void expand();
private:
int size;
double *arr;
void setSize(int value);
};
#endif // MYARRAY_H_INCLUDED
That's my myArray.cpp class where I'm getting the error in the default paramaterized constructor
#include "myArray.h"
#include <iostream>
using namespace std;
myArray::myArray() : size(0) {
// size = 10;
arr = new double [size];
}
/*myArray::myArray(int _size) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = i;
}
} */
myArray::myArray(int _size, double value) : size(_size) {
// size = _size;
arr = new double [size];
for (int i = 0; i < size; i++) {
arr[i] = value;
}
}
/*myArray::myArray(myArray* temp, int size)
{
setSize(temp.getSize());
for (int i = 0; i < getSize(); i++) {
setData(i, temp.getData(i));
}
} */
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
//double arr[size];
// arr = new double[size];
// p = orig;
// for(int i = 0;i<size;i++)
// {
// arr[i] = orig[i];
// cout << arr[i] << " ";
// }
// cout << endl;
// setSize(size);
// for (int i = 0; i < getSize(); i++)
// setData(i, orig.getData(i));
// cout << "hell";
// for (int i = 0; i < size; i++) {
// arr[i] = myArray[i];
// cout << arr[i];
//}
// arr = myArray;
}
myArray::~myArray() {
delete [] arr;
}
int myArray::getSize() const {
return size;
}
void myArray::setSize(int value) {
if (value > 0) {
size = value;
}
}
void myArray::setData(int index, double value) {
if ((index >= 0) && (index < size)) {
arr[index] = value;
} else {
// cout << "NO!" << endl;
}
}
double myArray::getData(int index) const {
if ((index >= 0) && (index < size)) {
return arr[index];
} else {
return arr[size - 1];
}
}
void myArray::print() const {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void myArray::expand() {
double *localArray = new double[size + 1];
for (int i = 0; i < size; i++) {
localArray[i] = arr[i];
}
localArray[size] = size;
delete [] arr;
setSize(size + 1);
arr = localArray;
// myArray = new int[size];
//
// //Is this a deep-copy or a shallow-copy?
// //Can you replace one with the other?
// //What are the advantages and disadvantages?
// for(int i=0; i < size; i++) {
// myArray[i] = localArray[i];
// }
// delete [] localArray;
}
bool myArray::equal(const myArray& rhs) const {
bool result(true);
if (getSize() != rhs.getSize()) {
result = false;
} else {
for (int i = 0; i < getSize(); i++) {
if (getData(i) != rhs.getData(i)) {
result = false;
}
}
}
return result;
}
void myArray::init()
{
cout << "Enter the " << size << " elements to populate the array " << endl;
for(int i = 0;i<getSize();i++)
{
int value;
cin >> value;
setData(i,value);
}
}
Sorry I somehow I thought you wanted help with a runtime error but you want help with the compile errors.
The compile error in this part of the code
myArray::myArray(double* orig, int size) {
setSize(orig.getsize());
for(int i = 0; i<getSize();i++)
setData(i,orig.getData(i));
is specifically about the orig.getSize() part. orig is of type double* (pointer to double) and pointers do not have member functions only classes do which is why the compiler says: "which is non-class type double"
Actually there is no way in c++ to know from a pointer to how many elements it points but luckily your function already has a parameter size which i guess is meant to pass in the size of the orig array. So that line should be setSize(size);
Now two lines lower you get a similar error on setData(i,orig.getData(i)); orig is still a double* so it still doesn't have member functions. The correct way is setData(i, orig[i]);
EDIT:
BTW, i quick look through the rest of your code shows me that your setSize method doesn't allocate an array of appropriate size so you should fix that to.

How to initialize a class Object of Typename T?

For a C++ class I am taking, I am creating a Vector Library. We are not allowed to use the built in vector library, of course, and I have decided to use arrays in my 'myvector' class.
I am currently trying to test my code and I am not sure how to create an object of class myvector.
The error I get is Incomplete type is not allowed.
main.cpp:
#include "my_vectorHeader.h"
using namespace std;
int main(){
myvector<int> vector = new myvector<int>(3);
}
my_vectorLib.cpp:
#include "my_vectorHeader.h"
#include iostream
#include exception
using namespace std;
template<typename T> class myvector {
private:
int vector_size, //holds current size
vector_capacity; //holds current capacity
public:
//constructors
myvector<T>(int length){
T vector[length];
vector_size = length;
vector_capacity = length;
}
myvector<T>(const T& doppelganger){
T vector = doppelganger;
while(vector[vector_size] != NULL)
vector_size++;
}
myvector<T>(const T& dat_arr, int arr_size){
vector_size = arr_size;
vector_capacity = arr_size;
for(int i = 0; i < arr_size; i++)
vector[i] = dat_arr[i];
}
~myvector(){ //destructor
delete [] vector;
delete myvector;
}
myvector& myvector::operator[](int index){ //override []
try{
throw vector[index];
} catch(exception e){
cout << e.what() << endl;
}
return vector[index];
}
T at(int index){
return vector[index];
}
int size(){
return vector_size;
}
int capacity(){
return vector_capacity;
}
bool empty(){
if(size() > 0)
return false;
else
return true;
}
void resize(int new_size){
T vector_copy[new_size];
for(int i = 0; i < new_size; i++){
if(i >= vector_size)
vector_copy[i] = NULL;
else
vector_copy[i] = vector[i];
if(new_size > capacity)
capacity = new_size;
}
vector_size = new_size;
delete [] vector;
T *vector;
vector = vector_copy;
for(int i = 0; i < vector_size; i++)
vector[i] = vector_copy[i];
delete [] vector_copy;
}
void reserve(int new_capacity){
if(new_capacity < vector_size){
cout << "Error. Newly provided vector capacity is smaller than the current vector size. The capacity is " << vector_capacity << " and has not been changed.";
} else {
vector_capacity = new_capacity;
}
}
T pop_back(){
T return_val = vector[size() - 1];
resize(size() - 1);
return return_val;
}
void push_back(T new_val){
resize(size() + 1);
vector[size() - 1] = new_val;
}
void assign(int position, T new_val){
vector[position] = new_val;
}
void clear(){
for(int i = 0; i < size(); i++)
vector[i] = NULL;
}
void erase(int position){
vector[position] = NULL;
do{
vector[position] = vector[position + 1];
}while(position != NULL);
resize(size() - 1);
}
void erase(int in, int between){
int i = in + 1, j = between;
while(i < between){
vector[i] = vector[j];
vector[j] = NULL;
i++, j++;
}
resize(between);
}
void insert(int index, T new_val){
for(int i = size + 1; i > index; i--)
vector[i] = vector[i - 1];
vector[index] = new_val;
}
};
Declaration and implementation of templates should be in the same file(or implementation should be included too). Also this
myvector<int> vector = new myvector<int>(3);
is incorrect(new returns pointer) and unnecessary. Just use
myvector<int> vector(3);
Put the class (all the code) found at my_vectorLib.cpp in your my_vectorLib.h As #soon pointed you, templates classes (unless specialized) need to be at the header file (the one you include at main.cpp which where the class is instantiated, which means the compiler generates the actual code when you use the template).