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
Related
Below is code for a simple book list with a class to store book names and isbn numbers into an overloaded function using a vector. This program runs fine and I can test it by returning a specific name (or isbn) using an accessor function from my class.
Question: I tried calling (instantiating?) a constructor with parameters from my class but it would not work, so I commented it out. Yet I was still able to run the program without error. From my main below - //BookData bkDataObj(bookName, isbn);
From watching tutorials, I thought I always had to make an object for a specific constructor from a class that I needed to call? My program definitely still uses my overloaded constructor and function declaration BookData(string, int); without making an object for it in main first.
Thanks for any help or input on this matter.
Main
#include <iostream>
#include <string>
#include <vector>
#include "BookData.h"
using namespace std;
int main()
{
string bookName[] = { "Neuromancer", "The Expanse", "Do Androids Dream of Electric Sheep?", "DUNE" };
int isbn[] = { 345404475, 441569595, 316129089, 441172717 };
//BookData bkDataObj(bookName, isbn); //how did program run without instantiating object for class?
vector <BookData> bookDataArr;
int arrayLength = sizeof(bookName) / sizeof(string);
for (int i = 0; i < arrayLength; i++) {
bookDataArr.push_back(BookData(bookName[i], isbn[i]));
}
cout << "Book 4 is: " << bookDataArr[3].getBookNameCl(); //test if works
return 0;
}
BookData.h
#include <iostream>
#include <string>
using namespace std;
class BookData
{
public:
BookData();
BookData(string, int); //wasn't I supposed to make an object for this constructor in my main?
string getBookNameCl();
int getIsbnCl();
private:
string bookNameCl;
int isbnCl;
};
BookData.cpp
#include "BookData.h"
BookData::BookData() {
bookNameCl = " ";
isbnCl = 0;
}
BookData::BookData(string bookNameOL, int isbnOL) { //how did I use this function
bookNameCl = bookNameOL; //definition without an object in main?
isbnCl = isbnOL;
}
string BookData::getBookNameCl() { //can still return a book name
return bookNameCl;
}
int BookData::getIsbnCl() {
return isbnCl;
}
I am learning classes and OOP, so I was doing some practice programs, when I came across the weirdest bug ever while programming.
So, I have the following files, beginning by my class "pessoa", located in pessoa.h:
#pragma once
#include <string>
#include <iostream>
using namespace std;
class pessoa {
public:
//constructor (nome do aluno, data de nascimento)
pessoa(string newname="asffaf", unsigned int newdate=1996): name(newname), DataN(newdate){};
void SetName(string a); //set name
void SetBornDate(unsigned int ); //nascimento
string GetName(); //get name
unsigned int GetBornDate();
virtual void Print(){}; // print
private:
string name; //nome
unsigned int DataN; //data de nascimento
};
Whose functions are defined in pessoa.cpp
#include "pessoa.h"
string pessoa::GetName ()
{
return name;
}
void pessoa::SetName(string a)
{
name = a;
}
unsigned int pessoa::GetBornDate()
{
return DataN;
}
void pessoa::SetBornDate(unsigned int n)
{
DataN=n;
}
A function, DoArray, declared in DoArray.h, and defined in the file DoArray.cpp:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
pessoa** pointer= &p;
return pointer;
}
And the main file:
#include <string>
#include <iostream>
#include "pessoa.h"
#include "DoArray.h"
#include <cstdio>
using namespace std;
int main()
{
//pessoa P[10];
//cout << P[5].GetBornDate();
pessoa** a=DoArray(5);
cerr << endl << a[0][3].GetBornDate() << endl;
cerr << endl << a[0][3].GetName() << endl;
return 0;
}
The weird find is, if I comment one of the methods above, "GetBornDate" or GetName, and run, the non-commented method will run fine and as supposed. However, if both are not commented, then the first will run and the program will crash before the 2nd method.
Sorry for the long post.
Let's look into this function:
int *get()
{
int i = 0;
return &i;
}
what is the problem with it? It is returning pointer to a local variable, which does not exist anymore when function get() terminates ie it returns dangling pointer. Now your code:
pessoa** DoArray(int n)
{
pessoa* p= new pessoa[n];
return &p;
}
do you see the problem?
To clarify even more:
typedef pessoa * pessoa_ptr;
pessoa_ptr* DoArray(int n)
{
pessoa_ptr p= whatever;
return &p;
}
you need to understand that whatever you assign to p does not change lifetime of p itself. Pointer is the same variable as others.
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 am supposed to write a program that simulates a dice(6 faced) roll 6000 times and stores the results in a vector. For example if the dice roll returns 1, I would do something like frequency.at(0)++. Since the size of the vector is gonna be fixed, and I would also need to able to access each element freely, I was wondering if there was anyway to declare the size of the vector using a default constructor or something. This is what I currently have but I get a "too many arguments in function call" and "expression must have class type" error. Maybe what I'm trying to do is not possible, I don't know, but just looking for some help. Thanks.
My header file:
#ifndef AHISTOGRAM_H
#define AHISTOGRAM_H
class aHistogram
{
public:
aHistogram();
~aHistogram();
void update(int face);
void display(int maxLengthOfLine);
void clear() const;
int count(int face);
private:
vector<int> numRolls();
int numx, m, j;
};
#endif
aHistogram.cpp:
#include <iostream>
#include <cstdlib>
#include <vector>
#include "aHistogram.h"
using namespace std;
aHistogram::aHistogram()
{
numRolls(6);
numx, m, j = 0;
}
aHistogram::~aHistogram()
{
}
void aHistogram::update(int face)
{
numRolls.at(face - 1)++;
return;
}
This is what the constructor's initializer list is for:
aHistogram::aHistogram(): numRolls(6), numx(0), m(0), j(0) // constructor parameters here
{
// numRolls(6);
// numx m, j = 0;
}
Also the declaration of your vector is wrong in your class definition:
class aHistogram
{
public:
aHistogram();
~aHistogram();
void update(int face);
void display(int maxLengthOfLine);
void clear() const;
int count(int face);
private:
// vector<int> numRolls(); // this is declaring a function!
vector<int> numRolls; // USE THIS!!
int numx, m, j;
};
IF the size of the "vector" is fixed, then using std::array is most certainly a better option, unless of course, you are using an ancient compiler which doesn't support C++11.
Go through the above link on cppreference.com. For most part, it is just like an "old fashioned" array, but it also comes with benefits such as bounds checking (if you use at() instead of operator[]), ability to iterate through elements (begin(), end(), etc.), and many other "benefits" of std::vector.
Have a look at this:
#include <iostream>
#include <array>
using namespace std;
class aHistogram {
public:
aHistogram() : numRolls{0, 0, 0, 0, 0, 0} {}
int count(int face) {
return numRolls.at(face - 1);
}
void update(int face) {
numRolls.at(face - 1)++;
}
private:
array<int, 7> numRolls;
};
int main() {
aHistogram ah;
ah.update(1);
ah.update(2);
ah.update(1);
cout << "Count[1]: " << ah.count(1) << " Count[2]: " << ah.count(2) << endl;
}
Hey guys I'm working on a project and I was doing pretty well until I hit this wall..
I am getting two errors:
error: 'binarySearch' was not declared in this scope
error: 'addInOrder' was not declared in this scope
Here are my files, I've tried quite a few things with no avail. Help would be much appreciated.
histogram.cpp
#include "histogram.h"
#include "countedLocs.h"
//#include "vectorUtils.h"
#include <string>
#include <vector>
using namespace std;
void histogram (istream& input, ostream& output)
{
// Step 1 - set up the data
vector<CountedLocations> countedLocs;
// Step 2 - read and count the requested locators
string logEntry;
getline (input, logEntry);
while (input)
{
string request = extractTheRequest(logEntry);
if (isAGet(request))
{
string locator = extractLocator(request);
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
/** Hint - when looking CountedLocations up in any kind
of container, we really don't care if the counts match up
or not, just so long as the URLs are the same. ***/
if (position >= 0)
{
// We found this locator already in the array.
// Increment its count
++countedLocs[position].count;
}
else
{
// This is a new locator. Add it.
CountedLocations newLocation (locator, 1);
addInOrder (countedLocs, newLocation);
}
}
getline (input, logEntry);
}
// Step 3 - write the output report
for (int i = 0; i < countedLocs.size(); ++i)
output << countedLocs[i] << endl;
}
countedLocs.cpp
#include "countedLocs.h"
#include <iostream>
#include <vector>
using namespace std;
int CountedLocations::binarySearch(const vector<CountedLocations> list, CountedLocations searchItem)
{
//Code was here
}
int CountedLocations::addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value)
{
//Code was here
}
countedLocs.h
#ifndef COUNTEDLOCATIONS
#define COUNTEDLOCATIONS
#include <iostream>
#include <string>
#include <vector>
struct CountedLocations
{
std::string url;
int count;
CountedLocations (){
url = "";
count = 0;
}
CountedLocations(std::string a, int b){
url = a;
count = b;
}
int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
int binarySearch (const std::vector<CountedLocations> list, CountedLocations searchItem);
};
inline
std::ostream& operator<< (std::ostream &out, CountedLocations& cL)
{
//out << "URL: " << cL.url << " count: " << cL.count << std::endl;
out << "\"" << cL.url << "\"," << cL.count;
return out;
}
#endif
The methods are member methods of CountedLocations... use something.extractLocator and something.binarySearch or make the histogram() to be also a member method of CountedLocations... (something is of type CountedLocations highly possibly will be countedLocs[position])
You have a free function histogram in which you are trying to use two member functions, addInOrder and binarySearch. In order to use them, you need to have an instance of CountedLocations.
If these are some kind of helper functions, which do not depend on the actual CountedLocations instance, I would turn them into static functions like this (you only need to change the header):
static int addInOrder (std::vector<CountedLocations>& vectr, CountedLocations value);
And then you can call this function by specifying the type of your class:
CountedLocations::addInOrder(...);
You are trying to call member methods of a struct without an object of that type. Strange.
You need to look at what a namespace is.
You declare a class CountedLocations, so far so good. But then you try to use the member functions outside the CountedLocations namespace which will obviously never work.
int position = binarySearch (countedLocs,
CountedLocations(locator, 0));
binarySearch is a member function of the CountedLocations namespace. If you want to call that function you have to create an object that contains a reference to that member function.
CountedLocation myObject;
int position = myObject.binarySearch (countedLocs, CountedLocations(locator, 0));
I dont know if that solves your problem, but you should know this before you even attempt to solve a problem.