how to have a copy constructor for vector? - c++

I simulated a vector but the constructor doesn't work; when I call pop() function it assigns garbage value to my old object in vector class.
vector(vector &v) {
vec = new T[v.size()];
memcpy(vec, v,v.size());
size_arr = v.size();
}
here's entire code:
#include <iostream>
using namespace std;
template <typename T>
class vector {
int size_arr;
T * vec = new T;
public:
vector(/*int _size*/) {
vec = new T[0];
size_arr = 0;
};
~vector() {
size_arr = 0;
delete[] vec;
};
vector(vector &v) {
vec = new T[v.size()];
memcpy(vec, v,v.size());
size_arr = v.size();
}
void push_back(T data) {
T *temp = new T[size_arr + 1];
for (int i = 0; i < size_arr; i++)
temp[i] = vec[i];
temp[size_arr] = data;
size_arr++;
delete[] vec;
vec = temp;
};
void push_front(T data){
int j;
T *temp = new T[size_arr + 1];
for ( j = size_arr; j >= 0;j--) {
temp[j + 1] = vec[j];
}
temp[0] = data;
delete[] vec;
vec = temp;
size_arr++;
};
void insert(int index, T data) {
int j;
T *temp = new T[size_arr + 1];
for (int i = 0; i < size_arr ;i++)
temp[i] = vec[i];
for (int i = 0; i < size_arr;i++) {
if (i == index) {
for ( j = size_arr; j >=i;j--) {
temp[j+1] = vec[j];
}
temp[j + 1] = data;
delete[] vec;
vec = temp;
size_arr++;
}
}
};
void pop() {
T *temp = new T[size_arr - 1];
for (int i = 0; i < size_arr-1;i++)
temp[i] = vec[i];
size_arr--;
delete[] vec;
vec = temp;
};
void Delete(int index)
{
T *temp = new T[size_arr - 1];
for (int i = 0; i < index;i++)
temp[i] = vec[i];
for (int i = 0; i < size_arr;i++) {
if (i == index) {
for (int j = i; j < size_arr-1;j++) {
temp[j] = vec[j + 1];
}
size_arr--;
delete[] vec;
vec = temp;
}
}
};
int search(T data) {
for (int i = 0; i < size_arr;i++) {
if (vec[i] == data) {
return i;
}
}
return -1;
};
int size() { return size_arr; };
};
int main() {
vector <int>test;
test.push_front(2);
test.push_front(3);
test.push_back(0);
test.push_back(-1);
test.insert(2, 2);
test.pop();
vector <int > test1;
test1 = test;// problem
test1.pop();
}

The problem is the line test1 = test;// problem, which does not call the copy constructor, but the assignment operator. You did not declare this operator, so the compiler will use the default implementation, which simply copies all member. So, after the assignment test1.vec and test.vec point to the same memory location.
When you change the line (and the one above it) to vector <int > test1{test};, it will call your copy constructor.
You also forgot to #include <cstring> for memcpy, which you should not use for non-POD types.
You have to multiply the size in memcpy with sizeof(T), because memcpy works on bytes, not on types. You also have to use v.vec instead of v.
Here is the fixed version: https://ideone.com/JMn7ww

I think the problem is in your copy operator. You use memcpy() which is a c function. Which should in itself not be a problem (apart from it being not so nice in many opinions). But since memcpy() is a c function, it doesn't know about types, and it takes its size arguments as a count of bytes.
the element you put in is int which is probably 4 bytes. So when your copy contstructor gets called, and the original has 3 elements, there will be 12 bytes in your array, but malloc will only copy 3 of them.
The comments of other people about not properly copying template types are right, so if you make a vector of strings, you cannot just memcpy them, and assume the result will be new strings. For this answer i was assuming you using only basic types as your template arguments like int, or double.

Related

Problem with printing copy constructor OOP

Having trouble with the printing copy constructors elements from Arr s to Arr s1 , also having troubles with << operator it doesn't work, please help cuz I am not pro just a student.
#include <iostream>
using namespace std;
class Arr {
private:
int size;
int *arr;
public:
Arr(int size,int *arr) {
this->size = size;
this->arr = new int [size];
for (int i = 0; i < size ; ++i) {
this->arr[i] = arr[i];
}
}
~Arr() {
delete[] arr;
}
Arr(const Arr &x) {
this->size = x.size;
this->arr = new int[x.size];
for (int i = 0; i < x.size; ++i) {
this->arr = x.arr;
}
}
Arr() : size(0),arr(0) {}
Arr(Arr &&x) {
this->size = x.size;
this->arr = new int[x.size];
for (int i = 0; i < x.size; ++i) {
this->arr = x.arr;
}
}
friend ostream &operator<<(ostream &out, const Arr &t) {
out << t.size;
for (int i = 0; i < t.size; i++) {
out << t.arr[i];
}
return out;
}
friend istream &operator>>(istream &in, Arr &t) {
in >> t.size;
for (int i = 0; i < t.size; ++i) {
in >> t.arr[i];
}
return in;
}
};
int main() {
int size = 3;
int arr [] = {1,2,3};
Arr s1(size,arr);
cin << s1;
cout<<s1;
Arr s(s1);
cout<<s; // not working at all
return 0;
}
You are writing
this->arr = x.arr;
in the copy constructor, rather than
this->arr[i] = x.arr[i];
That is, currently your code is copying the array pointer, not the elements of the array.
When you're debugging, first look over your code to make sure each part is doing what you want it to do and that you didn't make a typo like this. Then, if you don't find the problem, you can use a debugger like gdb to step through your code and monitor the values of the variables to make sure your program is doing what you'd like.

Why this move construct have not been called?

I have wrote a useless class, containing move constructor, default constructor and other construct. But this code (useless four(one + two)) didn't call move constructor. By the way, I have another question. Is safe when I delete a null pointer?
class useless {
private:
int len;
char * p; // address of string
public:
~useless();// default deconstruct
explicit useless(int len);// len construct
useless(int len, char c);// two argument construct
useless(useless&& u); //move construct
useless operator+(const useless& u) const; // operator +
};
useless::useless(int l) {
len = l;
p = new char[len];
}
useless::useless(int l, char c) {
len = l;
p = new char[len];
for(int i =0;i<len;i++){
p[i] = c;
}
}
useless::useless(useless&& u) {//move construct
len = u.len;
p = u.p;
u.p = nullptr;
u.len = 0;
}
useless::~useless() {
delete[] p;
}
useless useless::operator+(const useless &u) const {
useless re = useless(n + u.n);
for(int i =0; i < n; i++){
re.p[i] = p[i];
}
for(int i = n;i < re.n; i++){
re.p[i] = u.p[i - n];
}
return re;
}
int main(){
useless one(2,'x');
useless two = one;
useless four(one + two);
}

How do I fix this error? CRT detected that the application wrote to memory after end of heap buffer

I've been trying to make a dynamic array. My main method calls push_back() to add ints to an array 50 times. The push_back() method calls the grow_if_needed() method if the size of the array needs to be doubled. The size() method returns the current capacity of the array. And the toString method is for printing the array as a string. I keep getting this error at the end of the grow_if_needed() method.
#include <string>
class ArrayList
{
private:
static int capacity;
static int count;
public:
int& operator [](int i);
int *arrayPtr = new int[1];
ArrayList();
int * push_back(int m);
int * grow_if_needed();
int * erase(int m);
int size();
std::string toString();
};
#include "ArrayList.h"
using namespace std;
int ArrayList::capacity = 1;
int ArrayList::count = 0;
int & ArrayList::operator[](int i)
{
return arrayPtr[i];
}
ArrayList::ArrayList()
{
arrayPtr[0] = 0;
}
int * ArrayList::push_back(int m)
{
if (count == size()) {
grow_if_needed();
}
for (int i = size() - 1; i >= 0; i--) {
arrayPtr[i + 1] = arrayPtr[i];
}
arrayPtr[0] = m;
count++;
return arrayPtr;
}
int * ArrayList::grow_if_needed() {
int k;
capacity = size() * 2;
int * tempArray = new int[capacity];
for (k = 0; k < count; k++) {
tempArray[k] = arrayPtr[k];
}
while (k != capacity) {
tempArray[k] = 0;
k++;
}
delete [] arrayPtr;
arrayPtr = tempArray;
return arrayPtr;
}
int ArrayList::size()
{
return capacity;
}
string ArrayList::toString()
{
string num = "";
for (int i = 0; i <= size() - 1; i++) {
num += std::to_string(arrayPtr[i]) + " ";
}
return num;
}
In your push_back function you have this loop:
for (int i = size() - 1; i >= 0; i--) {
arrayPtr[i + 1] = arrayPtr[i];
}
Here size() - 1 is the top index, so in the first iteration when you do i + 1 you are out of bounds.
Also, this function is called push_back, but it attempts to add to the front? If it added to the end (the "back") you would not need the loop, and your problem would "magically" disappear.

C++ error reading character of string

I am trying to add an array to my Object which contains dynamic array
MyCollection.h
template <typename T>
MyCollection<T>::MyCollection(int size)
{
arraySize = size;
anArray = new T[size];
}
template <typename T>
MyCollection<T>::MyCollection(MyCollection<T>& coll)
{
arraySize = coll.arraySize;
anArray = new T[arraySize];
for (int i = 0; i < arraySize; i++)
{
SetValue(coll.GetValue(i), i);
}
}
template <typename T>
MyCollection<T>::MyCollection(T* myArray, int size)
{
anArray = myArray;
arraySize = size;
}
template<typename T>
void MyCollection<T>::AddAll(T pArray[], int size)
{
int plusSize = size - 1;
int arrayIterator = 0;
arraySize += size;
for (int i = size; i < arraySize - plusSize; i++)
{
anArray[i] = pArray[arrayIterator];
arrayIterator++;
}
}
Main
MyCollection<string> B = MyCollection<string>(new string[3], 3);
B.SetValue("C", 0);
B.SetValue("D", 1);
B.SetValue("E", 2);
string C[3];
C[0] = "X";
C[1] = "Y";
C[2] = "Z";
B.AddAll(C, 3);
B.Display();
In the AddAll method I have error with acces violation. When I add watch anArray[i] = . Is there any idea why that happens? Is it problem with copy construcotr or so ?
In AddAll(), you need to resize the raw array anArray, there is no resizing going on (you just change the numeric value of arraySize, but do not allocate more memory). So you need something like
delete[] anArray;
// ...
anArray = new T[arraySize];
You may also think whether you want to copy the old elements into the newly allocated array, in which case you first have to reallocate with a temporary pointer, then copy into it, then delete the original anArray, and finally assign the temporary pointer to the original anArray, something like:
// save the old size
int oldSize = arraySize;
arraySize += size;
T* tmp = new T[arraySize];
// copy from anArray into tmp, use oldSize
// for(...){...}
delete[] anArray;
anArray = tmp;

How to avoid returning pointers in a class

Assume I have a class A that has say 3 methods. So the first methods assigns some values to the first array and the rest of the methods in order modify what is computed by the previous method. Since I wanted to avoid designing the methods that return an array (pointer to local variable) I picked 3 data member and store the intermediate result in each of them. Please note that this simple code is used for illustration.
class A
{
public: // for now how the class members should be accessed isn't important
int * a, *b, *c;
A(int size)
{
a = new int [size];
b = new int [size];
c = new int [size];
}
void func_a()
{
int j = 1;
for int(i = 0; i < size; i++)
a[i] = j++; // assign different values
}
void func_b()
{
int k = 6;
for (int i = 0; i < size; i++)
b[i] = a[i] * (k++);
}
void func_c()
{
int p = 6;
for int (i = 0; i < size; i++)
c[i] = b[i] * (p++);
}
};
Clearly, if I have more methods I have to have more data members.
** I'd like to know how I can re-design the class (having methods that return some values and) at the same time, the class does not have the any of two issues (returning pointers and have many data member to store the intermediate values)
There are two possibilities. If you want each function to return a new array of values, you can write the following:
std::vector<int> func_a(std::vector<int> vec){
int j = 1;
for (auto& e : vec) {
e = j++;
}
return vec;
}
std::vector<int> func_b(std::vector<int> vec){
int j = 6;
for (auto& e : vec) {
e *= j++;
}
return vec;
}
std::vector<int> func_c(std::vector<int> vec){
//same as func_b
}
int main() {
std::vector<int> vec(10);
auto a=func_a(vec);
auto b=func_b(a);
auto c=func_c(b);
//or in one line
auto r = func_c(func_b(func_a(std::vector<int>(10))));
}
Or you can apply each function to the same vector:
void apply_func_a(std::vector<int>& vec){
int j = 1;
for (auto& e : vec) {
e = j++;
}
}
void apply_func_b(std::vector<int>& vec){
int j = 6;
for (auto& e : vec) {
e *= j++;
}
}
void apply_func_c(std::vector<int>& vec){
// same as apply_func_b
}
int main() {
std::vector<int> vec(10);
apply_func_a(vec);
apply_func_b(vec);
apply_func_c(vec);
}
I'm not a big fan of the third version (passing the input parameter as the output):
std::vector<int>& func_a(std::vector<int>& vec)
Most importantly, try to avoid C-style arrays and use std::vector or std::array, and don't use new, but std::make_unique and std::make_shared
I'm assuming you want to be able to modify a single array with no class-level attributes and without returning any pointers. Your above code can be modified to be a single function, but I've kept it as 3 to more closely match your code.
void func_a(int[] arr, int size){
for(int i = 0; i < size; i++)
arr[i] = i+1;
}
void func_b(int[] arr, int size){
int k = 6;
for(int i = 0; i < size; i++)
arr[i] *= (k+i);
}
//this function is exactly like func_b so it is really unnecessary
void func_c(int[] arr, int size){
int p = 6;
for(int i = 0; i < size; i++)
arr[i] *= (p+i);
}
But if you just want a single function:
void func(int[] arr, int size){
int j = 6;
for(int i = 0; i < size; i++)
arr[i] = (i+1) * (j+i) * (j+i);
}
This solution in other answers is better, if you are going to allocate memory then do it like this (and test it!) also if you are not using the default constructor and copy constructor then hide them, this will prevent calling them by accident
class A{
private:
A(const &A){}
A() {}//either define these or hide them as private
public:
int * a, *b, *c;
int size;
A(int sz) {
size = sz;
a = new int[size];
b = new int[size];
c = new int[size];
}
~A()
{
delete[]a;
delete[]b;
delete[]c;
}
//...
};