creating vector using templates in cpp - c++

This is example from a text book. We are creating vector using templates. in main function we copy the predefined array into vectors. Finally, we multiply two vectors. Although program compiles nicely the program fails to execute. Whats wrong with the code.
#include <iostream>
const int size = 3;
template<class T>
class vector
{
T* v;
public:
vector()
{
v = new T[size];
for (int i = 0; i < size; i++){
v[i] = 0;
}
}
vector(const T* a)
{
for (int i = 0; i < size; i++){
v[i] = a[i];
}
}
T operator * (const vector& y)
{
T sum = 0;
for (int i = 0; i < size; i++){
sum += this->v[i] * y.v[i];
}
return sum;
}
};
int main()
{
int x[3] = { 1, 2, 3 };
int y[3] = { 4, 5, 6 };
vector<int> v1;
vector<int> v2;
v1 = x;
v2 = y;
int R = v1 * v2;
std::cout << R;
return 0;
}

First of all in this constructor
vector(T *a)
{
for(int i=0;i<size;i++){
v[i]= a[i];
}
}
you did not allocate the array pointed to by v. Pointer v is not initialized. So the constructor has undefined behaviour.
And another potential problem is that you did not define the copy assignment operator.
In these statements
v1 = x; v2 = y;
temporary objects of type vector are created and after the assignment they will be deleted. Thus the new created objects will have invalid pointer v.
You have to define at least copy constructor, copy assignment operator and destructor.

Related

how to have a copy constructor for vector?

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.

No viable conversion from Array<float> to Array<int>

#include <iostream>
using namespace std;
template<class T>
class Array {
public: // should be private, big ignore that
int n;
T *arr;
public:
Array(int sz, T initValue) {
n = sz;
arr = new T[n];
for (int i=0; i<n; i++) arr[i] = initValue;
}
Array& operator = (const Array& b) {
if (this!=&b) {
delete[] arr;
n = b.n;
arr = new T[n];
for (int i=0;i<n;i++) arr[i] = b.arr[i];
}
return *this;
}
Array operator + (const Array& b) {
Array res(n, 0);
for (int i=0; i<n;i++) res.arr[i] = arr[i] + b.arr[i];
return res;
}
};
int main()
{
Array<double> a(10, 1); //Array<double> b(10, 2); // this works
Array<int> b(10, 2);
a = b; // error
for (int i=0; i<10; i++) cout << i << " " << a.arr[i] << "\n";
Array<double> c(10,0);
c = a + b; // error if b is <int>, runs if b is <double>
c = a - b;
c = a * b;
}
So I have a template class that can takes int, float, double, ...
Intuitively, Array<double> a; Array<int> b; a = b; should be possible because element-wise, we can do a[i] = b[i]. However, I have the conversion error because something is missing.
How can I make a = b; possible? Thank you.
Edit: the point is not about making an Array. It can be a Matrix, 3dArray, etc. It's about assignment of a float template and int template. You can also replace int with float, and float with highPrecisionFloat, for example.
Edit 2: I forgot to mention, I not just only need operator =, but operator + (and - * /, etc) as well. If I user #churill answer, I need to do so for each operator. How can I make conversion from Array to Array implicit?
In the class template
template<class T>
class Array { ... }
The identifier Array refers actually to Array<T>. You will have to make operator== a template and you probably want to add an explicit cast:
template<typename TOther>
Array<T> &operator = (const Array<TOther>& b) {
if constexpr (std::is_same<T, TOther>::value) {
// only check for self-assignment T and TOther are the same type
if (this == &b)
{
return *this;
}
}
delete[] arr;
n = b.n;
arr = new T[n];
for (int i=0;i<n;i++)
arr[i] = static_cast<T>(b.arr[i]);
return *this;
}
Note that std::is_same is from the type_traits-header.

Array Class Printout of the array

I am trying to create a member function which print out the array that I control, but I am running into Seg fault. Any help would be really useful!
Here is my header file, all the code in there work except the last member function.
#include <iostream>
#include <assert.h>
using namespace std;
#ifndef _ARRAY_H
#define _ARRAY_H
template<class T>
class Array{
private:
T *a;
int length;
public:
// constructor
Array (int len){
length = len;
a = new T[length];
for (int i = 0; i < len; i++){
a[i]=0;
}
}
// destructor
~Array()
{delete[] a;}
// operator overload
T& operator [](int i){
assert (i>=0 && i < length);
return a[i];
}
// operator overload
Array<T>& operator=(Array<T> &b){
if (a !=nullptr) delete[] a;
a = b.a;
b.a = nullptr;
length = b.length;
return *this;
}
//get the length of the array
int arraylength(){
return length;
}
//------------------This below is where I am having issue --------//
//print out the array
Array<T> printarray(){
for (int i = 0; i < length; i++){
cout << a[i];
}
}
};
int main();
#endif
This is my main file
#include <iostream>
#include "../include/array.h"
using namespace std;
int main(){
// initialize array
Array <int> a(5);
Array <int> b(5);
// put stuff into array
for (int i = 0; i< a.arraylength(); i++){
a[i] = i;
}
// set b = a using operator overload
b = a;
// print out the result b array
for (int i = 0; i < b.arraylength(); i++){
cout << b[i] << endl;
}
a.printarray();
return 0;
}
Again. Thank you for the help, I am quite new to C++ and mostly self taught.
In this statement
b = a;
you have called operator= in which a pointer of a object was set to nullptr, but in printArray you don't check if a is not null, so you are accesing data for null pointer, it is undefined behaviour. Add the condition to check if array is not empty:
void printarray(){
if (!a) return; // <- array is empty
for (int i = 0; i < length; i++){
cout << a[i];
}
}
Secondly, return type of printArray should be void, you don't return any value in this function.
You should fix printarray by changing the return type to void and making it a const member function.
void printarray() const {
for (int i = 0; i < length; i++){
cout << a[i];
}
}
However, that is not the main problem in your code. The main problem is that you are not following the The Rule of Three.
You don't have copy constructor.
You have a copy assignment operator but it is not implemented properly.
The line
b = a;
causes problems downstream that can be fixed by following The Rule of Three.
Here's an implementation of the copy assignment operator function that should work.
// Make the RHS of the operator a const object.
Array<T>& operator=(Array<T> const& b)
{
// Prevent self assignment.
// Do the real assignment only when the objects are different.
if ( this != &b )
{
if (a != nullptr)
{
delete[] a;
a = nullptr;
}
// This is not appropriate.
// a = b.a;
// b.a = nullptr;
// b needs to be left untouched.
// Memory needs to be allocated for this->a.
length = b.length;
if ( length > 0 )
{
a = new T[length];
// Copy values from b to this.
for (int i = 0; i < length; ++i )
{
a[i] = b.a[i];
}
}
}
return *this;
}
Please note that you should implement the copy constructor also, and then use the copy swap idiam to implment the assignment operator.
Very relevant: What is the copy-and-swap idiom?

Adding two vectors using operator overloading

I got a class Vectors which has private dynamic array.
All I wanted to do is to add two Vectors objects like A = A + B, but the program keeps crashing.
This is declaration of my class:
class Vectors
{
private:
int* vector;
public:
Vectors(int);
Vectors(Vectors&);
~Vectors();
Vectors operator+(Vectors&);
};
This is my implementation:
#include "Vectors.h"
#include "iostream"
using namespace std;
Vectors::Vectors(int value)
{
this->vector = new int[3];
for (auto i = 0; i < 3; i++)
{
vector[i] = 3;
}
}
Vectors::Vectors(Vectorsy& copy)
{
this->vector = new int[3];
for (auto i = 0; i < 3; i++)
{
vector[i] = copy.vector[i];
}
}
Vectors::~Vectors()
{
delete[] vector;
}
Vectors Vectors::operator+(Vectors& obj) // There is sth wrong here.
{
for (auto i = 0; i < 3; i++)
this->vector[i] += obj.vector[i];
return *this;
}
This is the error I get:
I believe you need an operator= function. You haven't implemented it so the compiler writes a default one which does the wrong thing (due to the fact that the class has a pointer). Most likely the crash is occurring while deleting the same memory twice.
See What is The Rule of Three?
The problem was the copy Constructor (Vectors::Vectors(const Vectors& copy)
Hear a working code.
#include "iostream"
using namespace std;
class Vectors
{
private:
int* vector;
public:
Vectors(int);
Vectors(const Vectors&);
~Vectors();
Vectors operator+(Vectors&);
};
Vectors::Vectors(int value)
{
this->vector = new int[3];
for (auto i = 0; i < 3; i++)
{
vector[i] = 3;
}
}
Vectors::Vectors(const Vectors& copy)
{
this->vector = new int[3];
for (auto i = 0; i < 3; i++)
{
vector[i] = copy.vector[i];
}
}
Vectors::~Vectors()
{
delete[] vector;
}
Vectors Vectors::operator+(Vectors& obj) // There is sth wrong here.
{
for (auto i = 0; i < 3; i++)
this->vector[i] += obj.vector[i];
return *this;
}
int main()
{
Vectors A(3), B(3);
Vectors C = A+B;
}

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;
}
//...
};