Making an array class so they act like vectors - c++

I have to make a class that will make arrays act like vectors. When I try and pass the class into the method into my main I get an error telling me that "[" and "]" are incorrect operators. I was wondering if I'm just completely doing this wrong or if it's just a simple mistake. Help is greatly appreciated. Here is my header file:
#ifndef PROGRAM5HEADER_H
#ifndef PROGRAM5HEADER_H
#define PROGRAM5HEADER_H
#include <string>
using namespace std;
class FloatArray
{
int *rep;
int _size;
public:
FloatArray(int sz=100):_size(sz)
{
rep=new int[sz];
}
~FloatArray()
{
delete [] rep;
}
int size() const
{
return _size;
}
FloatArray(const FloatArray& x)
{
copy(x);
}
void copy(const FloatArray& x)
{
_size == x.size();
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
};
#endif
and here is my main program
#include <iostream>
#include <string>
#include <cstdlib>
#include "program5header.h"
#include <cmath>
using namespace std;
int meanstd(FloatArray x, int& std)
{
int sx=0,sx2=0,mean;
for(int i=0;i<x.size();i++)
{
sx+=x[i];
sx2+=x[i]*x[i];
}
mean=sx/x.size();
std=sqrt(sx2/x.size()-mean*mean);
return mean;
}
int main()
{ int f;
cout<<"How big of an array would you like: "<<endl;
cin>>f;
FloatArray x(f);
}

There are a lot of issues with a lot of your implementation, I'd suggest doing some research on the subject. I'll touch on a few.
Firstly, you should make your FloatArray a templated class and allow for different types other than just int.
When you initialize a FloatArray x and then try to access it's underlying array through "[]" you are actually invoking the following:
x.operator[](...)
You haven't defined the '[]' operator on your FloatArray class so you are getting an error.
You need something similar to this:
int FloatArray.operator[](int index) {
assert(index < _size);
return _rep[index]
}
Your copy isn't doing what you want, it's not copying the size over to "this". It should look something similar to this:
void copy(const FloatArray& x)
{
_size = x._size;
rep=new int[_size];
for(int k=0;k<_size;k++)
rep[k]=x.rep[k];
}
However I would suggest not having a copy method and instead implement everything in your copy constructor.

Related

How to copy elements from std::list to an array of struct?

I need to copy the contents of a std::list into an array, wherein the array is struct of array. Below is the code implementation of it.
#include <iostream>
#include <string>
using namespace std;
typedef struct
{
int height;
int width;
int length;
}dimensions;
GetDimensions(list<std::string>, *int); // Function that copies the content of list to array passed as second parameter
int main()
{
dimensions cuboid[10];
int plane[10];
list<std::string> planeList = GetList();//Function that returns list of elements
list<std::string> dimensionList = GetList();
GetDimensions(planeList,&plane);//This is fine, as it is a simple array
GetDimensions(dimensionList,&cuboid.height);//Trouble in implementation of this usecase, for cuboid.height, cuboid.width and cuboid.height.
return 0;
}
GetDimensions(list<std::string>dimensionList, int* dimensionParams)
{
int i=0;
for(list<std::string>::iterator it = dimensionList.begin(); it != dimensionList.end(); ++it)
{
dimensionParams[i] = stoi(*it);
i++;
}
}
Here, I need GetDimensions() function to copy the list (passed as first parameter) to array (second parameter). The implemented function works well for simple array plane. But how to pass the array of struct as parameter to the function ?
I will be getting the std::list as cuboid.height, cuboid.width and cuboid.length. So the function has to copy the contents of list from cuboid[0].height to cuboid[i].height respectively. Is there any specific function to copy the content directly?
Use std::array 's instead. Then your problem can be reduced to passing two different types of arrays to a single function.
This can be solved
either by good old function overloads
or in c++17 function template with
if-constexpr.
Following is an example code with templated function with if-constexpr (See live online)
#include <iostream>
#include <string>
#include <list>
#include <array>
#include <type_traits> // std::is_same_v
struct dimensions // no need to typedef here
{
int height;
int width;
int length;
};
template<typename T>
void GetDimensions(const list<std::string>& dimensionList, T& dimensionParams)
^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ //---> pass list by const-ref as the values are non-modifying
{
int i{0};
if constexpr (std::is_same_v<std::array<int, 10>, T>)
{
for(const std::string& str: dimensionList) dimensionParams[i++] = std::stoi(str);
}
else
{
for(const std::string& str: dimensionList) dimensionParams[i++].height = std::stoi(str);
}
}
int main()
{
std::array<dimensions, 10> cuboid; // use std::array instead of VLA
std::array<int, 10> plane;
std::list<std::string> planeList{"1", "2"}; // some list
std::list<std::string> dimensionList{"1", "2"};
GetDimensions(planeList, plane);
GetDimensions(dimensionList, cuboid);
return 0;
}
Also note that:
You have not specified the return type of GetDimensions function.
You probably want to return void there.
in C++ you do not need to use typedef alias for struct { ... }.
last but not least, do not practice with using namespace std;
You can do this with boost::transform_iterator.
#include <iostream>
#include <string>
#include <algorithm>
#include <functional>
#include <boost/iterator/transform_iterator.hpp>
struct dimensions {
int height;
int width;
int length;
};
template <typename OutputIt>
void GetDimensions(std::list<std::string> dimensionList, OutputIt dimensionParams)
{
// N.b. taking the address of a standard library function is undefined, so wrap in a lambda
auto stoi = [](std::string s){ return std::stoi(s); };
std::copy(boost::make_transform_iterator(dimensionList.begin(), stoi),
boost::make_transform_iterator(dimensionList.end(), stoi),
dimensionParams);
}
int main() {
dimensions cuboid[10];
int plane[10];
std::list<std::string> planeList = GetList();
std::list<std::string> heightList = GetList();
std::list<std::string> widthList = GetList();
std::list<std::string> lengthList = GetList();
GetDimensions(planeList, plane);
GetDimensions(heightList,
boost::make_transform_iterator(cuboid, std::mem_fn(&dimensions::height)));
GetDimensions(widthList,
boost::make_transform_iterator(cuboid, std::mem_fn(&dimensions::width)));
GetDimensions(lengthList,
boost::make_transform_iterator(cuboid, std::mem_fn(&dimensions::length)));
return 0;
}

Program stops - move array to function | C++

I have 2 classes.
First Class - Midgam - The constructor has the following line:
midgam = new Vector[20];
The second class - Vector - where I create an array named array.
The program works great just that I have a little problem.
At the end of the program I try to print in alphabetical order, I use the BubbleSort sorting. The sorting works fine but something in the Swap function stops.
This is how it looks:
void Midgam::Swap(Vector *xp, Vector *yp) {
Vector temp = *xp;
cout << temp.getName() << endl;
*xp = *yp;
*yp = temp;
}
void Midgam::bubbleSort() {
int i, j;
for (i = 0; i < iterator - 1; i++) {
for (j = 0; j < iterator - i - 1; j++) {
if (midgam[j].getName().compare(midgam[j+1].getName()) > 0) {
Swap(&midgam[j], &midgam[j+1]);
}
}
}
}
I work with Visual Studio, the program stops and the program shows me the following code snippet in the Vector class:
Vector::~Vector() {
if (array)
delete[] array;
}
full definitions of Midgam:
#include <iostream>
#include <string>
#include "Vector.h"
using namespace std;
#ifndef MIDGAM_H_
#define MIDGAM_H_
class Midgam {
private:
int boxNum;
int maxParties;
int iterator;
Vector *midgam;
public:
Midgam(int num_of_boxes, int num_of_parties);
virtual ~Midgam();
void Start();
void Menurmal();
void SumOfEzor();
double SumOfParty(string name);
int SumAllVotes();
void AddParty();
void Swap(Vector *xp, Vector *yp);
void bubbleSort();
void Histograma();
void PrintStars(int num);
int FindPartyByName(string party);
void PrintAll();
};
#endif /* MIDGAM_H_ */
full definitions of Vector:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#ifndef VECTOR_H_
#define VECTOR_H_
class Vector {
private:
string name;
int size;
unsigned int *array;
bool Bool;
public:
Vector(string name, int size);
Vector();
Vector & operator=(const Vector &);
virtual ~Vector();
bool StringToArray(string str);
bool getBool();
string getName();
unsigned int getAddress();
int getSize();
unsigned int getValueFromArray(int index);
double sumOfArray();
void PrintArray();
};
#endif /* VECTOR_H_ */
Does anyone know why it does not work? Thank you
Your Vector lacks a proper copy constructor.
Vector temp = *xp;
//NOT EQUAL TO:
//Vector temp;
//temp=*xp;
The above statement won't call operator=(const Vector &) even though there's an equal sign. The following line is correct and equivalent:
Vector temp(*xp);
The reason is that this is a copy initialization - temp is created and so a constructor must be called - in particular the copy constructor Vector(const Vector &). Which you did not explicitly declared and so a default one was used.
Then a shallow copy is made, temp and *xp then share the same array and when both their destructors get called the second one will try to delete already deleted memory - undefined behavior which triggers Visual Studio's debugger (at least in debug mode).
The solution is to do a proper deep copy - create a new array and copy its contents:
#include <algorithm> #Contains std::copy_n
Vector::Vector(const Vector& other)
{
name=other.name;
size=other.size;
//Creates a new array
array= new unsigned int[size];
//Copies the array contents
std::copy_n(other.array,size,array);
Boo=other.Bool;
}
Also this is a prime example of why not to use raw memory. I get that you are implementing custom vector and don't want to use std::vector for the array but at least use std::unique_ptr. If you would have just done that you wouldn't have to ask this question in the first place as the compiler would have complained and the debugger wouldn't have to do the compiler's job.

Structure Arrays & Pointers

I have to use a struct array called Robot_parts[] for each part_rect struct (part_num, part_name, part_quantity, part_cost)
And through the void display function, I have to display Robot_parts[] array entirely through pointer but I don't know how, and I don't know where to declare Robot_parts[] and whether i have to put any number value inside the brackets.
So far I have:
#include <iostream>
#include <string>
using namespace std;
void display();
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
int main()
{
part_rec Robot_parts[ ] = {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
return 0;
}
void display()
{
cout<<Robot_parts[]<<endl<<endl;
}
If I also made a few other errors, please let me know. Thanks!
As stated in a comment it would be much better to use a c++ container like a std::vector or std::array.
But since your professor requires an old-style array, you could try like the code below - see the comments for explanation:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct part_rec
{
int part_num;
string part_name;
int part_quantity;
double part_cost;
};
// You have to pass a pointer (to the array) and the size of the array
// to the display function
void display(part_rec* Robot_parts, int n);
// Make a function so that you can "cout" your class directly using <<
// Note: Thanks to #BaumMitAugen who provided this comment and link:
// It makes use of the so called Operator Overloading - see:
// https://stackoverflow.com/questions/4421706/operator-overloading
// The link is also below the code section
std::ostream &operator<<(std::ostream &os, part_rec const &m)
{
// Note - Only two members printed here - just add the rest your self
return os << m.part_num << " " << m.part_name;
}
int main()
{
part_rec Robot_parts[] {
{7789, "QTI", 4, 12.95},
{1654, "bolt", 4, 0.34},
{6931, "nut", 4, 0.25}
};
display(Robot_parts, 3);
return 0;
}
void display(part_rec* Robot_parts, int n)
{
// Loop over all instances of your class in the array
for (int i = 0; i < n; ++i)
{
// Print your class
cout << Robot_parts[i] << endl;
}
}
The link recommended by #BaumMitAugen:
Operator overloading

undefined reference to my constructor

I have a simple class which I cannot instantiate and I don't know why...
Please help me !
-------Test.cpp-------
#include<iostream>
using namespace std;
#include "meteo.h"
int main()
{
Meteo meteo;
}
-------meteo.h---------
#ifndef METEO_H
#define METEO_H
class Meteo
{
public:
Meteo();
int Get(int i);
private:
char *list[];
};
#endif
-------meteo.cpp--------
#include "meteo.h"
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
int Meteo::Get(int i)
{
return list[i];
}
I get the error: "undefined reference to `Meteo::Meteo()'"
It seems that the problem is that the compiler issued an error when was compiling the constructor
Meteo::Meteo()
{
list[]("Sec","Venteux","Humide");
}
and did not generate the object module.
This record
list[]("Sec","Venteux","Humide");
is invalid.
Try to change the class definition like
class Meteo
{
public:
Meteo();
int Get(int i);
private:
const char *list[3];
};
and define the constructor like
Meteo::Meteo() : list { "Sec","Venteux","Humide" }
{
}
The other reason might be that you did not include object module meteo in the project.
Take into account that this member function
int Meteo::Get(int i)
{
return list[i];
}
is also wrong. The type of elements of the array is const char * not int.

I am stuck with creating an output member function

I am stuck on the output member function of the class. I have no idea how to create it and just simply couting it does not seem to work. also any other advice would be great. thanks in advance
here's the code:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class StringSet
{
public:
StringSet(vector<string> str);
void add(string s);
void remove(int i);
void clear();
int length();
void output(ostream& outs);
private:
vector<string> strarr;
};
StringSet::StringSet(vector<string> str)
{
for(int k =0;k<str.size();k++)
{
strarr.push_back(str[k]);
}
}
void StringSet::add(string s)
{
strarr.push_back(s);
}
void StringSet::remove(int i)
{
strarr.erase (strarr.begin()+(i-1));
}
void StringSet::clear()
{
strarr.erase(strarr.begin(),strarr.end());
}
int StringSet::length()
{
return strarr.size();
}
void StringSet::output()
{
}
int main()
{
vector<string> vstr;
string s;
for(int i=0;i<10;i++)
{
cout<<"enter a string: ";
cin>>s;
vstr.push_back(s);
}
StringSet* strset=new StringSet(vstr);
strset.length();
strset.add("hello");
strset.remove(3);
strset.empty();
return 0;
}
Ok, you should begin by solving some errors in your code:
You use a pointer to StringSet and after that you are trying to access the member-functions with the . operator instead of the ->. Anyway, do you really need to allocated your object dynamically ?
StringSet strset(vstr); // No need to allocated dynamically your object
After that, you are calling an empty() method which does not exist...
Also if you stay on dynamic allocation, don't forget to deallocated your memory :
StringSet* strset = new StringSet(vstr);
// ...
delete strset; // <- Important
Finally, I think that your function output should write in the stream the content of your vector, you can do it that way :
#include <algorithm> // For std::copy
#include <iterator> // std::ostream_iterator
void StringSet::output( ostream& outs )
// ^^^^^^^^^^^^^ don't forget the arguments during the definition
{
std::copy(strarr.begin(), strarr.end(), std::ostream_iterator<string>(outs, "\n"));
}
HERE is a live example of your code fixed.
I would suggest you to understan how class works : http://www.cplusplus.com/doc/tutorial/classes/
If your output function is going to print the state of the StringSet object, you may implement is like this:
#include<iterator> //std::ostream_iterator
#include<algorithm> //std::copy
void StringSet::output(ostream& outs)
{
std::copy(starr.begin(), starr.end(), std::ostream_iterator<string>(outs, "\n"));
}