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"));
}
Related
#include <iostream>
using namespace std;
template<class T>
class Array{
public:
T U[10];
friend void DataOut(Array<string>);
friend void GetData(Array<string>);
};
void DataOut(Array<string> Array1){
cout << Array1.U[0];
}
void GetData(Array<string> Array1){
cin >> Array1.U[0];
cin.clear();
}
int main(){
Array<string> Arr1;
GetData(Arr1);
DataOut(Arr1);
}
I made a class template and created two functions: GetData for entering string and DataOut for printing that string, but after entering string it doesn't print it. What have I done wrong?
I placed comments where I made changes. The main fix is to pass your object by reference, especially to Getdata(). You passed a copy, put data into the copy, and when the function ended, the copy goes away and your original object was never touched.
#include <iostream>
using namespace std;
template <class T>
class Array {
public:
T U[10];
friend void DataOut(
const Array<string>&); // CHANGED: Need to take object by reference
friend void GetData(Array<string>&); // SAME
};
void DataOut(const Array<string>& Array1) { // SAME
cout << Array1.U[0];
}
void Getdata(Array<string>& Array1) { // SAME
cin >> Array1.U[0];
// cin.clear(); // CHANGED: Why?
}
int main() {
Array<string> Arr1;
Getdata(Arr1);
DataOut(Arr1);
}
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.
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
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.
I'm storing a map in a class that has strings as keys and pointers to member functions as values. I'm having trouble calling the right function throw the function pointer.
Here is the code:
#include <iostream>
#include <string>
#include <map>
using namespace std;
class Preprocessor;
typedef void (Preprocessor::*function)();
class Preprocessor
{
public:
Preprocessor();
~Preprocessor();
void processing(const string before_processing);
private:
void take_new_key();
map<string, function> srch_keys;
string after_processing;
};
Preprocessor::Preprocessor()
{
srch_keys.insert(pair<string, function>(string("#define"), &Preprocessor::take_new_key));
}
Preprocessor::~Preprocessor()
{
}
void Preprocessor::processing(const string before_processing)
{
map<string, function>::iterator result = srch_keys.find("#define");
if(result != srch_keys.end())
result->second;
}
void Preprocessor::take_new_key()
{
cout << "enters here";
}
int main()
{
Preprocessor pre;
pre.processing(string("...word #define other word"));
return 0;
}
In function Preprocessor::processing if the string is found in the map then, I call the proper function. The problem is that, in this code, Preprocessor::take_new_key is never called.
Where is the mistake ?
Thanks
The correct syntax is this:
(this->*(result->second))();
That is ugly. So lets try this:
auto mem = result->second; //C++11 only
(this->*mem)();
Use whichever makes you happy.
result->second does not call the function pointer. Try ((*this).*result->second)();