Read class objects directly into a vector in c++ - c++

So I've started learning vectors in c++, and I made this program, but I dont like the fact that I read the object data into a C style array, and then I transfer all the data into a vector.
Is it possible to read the data into the vector, without using the C style array?
This is my code:
#include <iostream>
#include <vector>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
class number
{
private:
std::string name;
float n1_;
int n2_;
public:
number() = default;
~number() = default;
public:
void read();
float perMonth(){return n1_ * n2_;}
float perYear(){return perMonth() * 12;}
std::string get_Name(){return name;}
};
void number::read()
{
cout << "Worker name: "; cin >> name;
n1_ = rand() % 100 + 3;
n2_ = rand() % 100 + 3;
}
int main()
{
int n;
cout << "Insert number of workers:"; cin >> n;
number pers[30];
for(int i = 0; i < n; i++)
pers[i].read();
std::vector<number> people;
for(int i = 0; i < n; i++)
people.push_back(pers[i]);
for(number pr : people)
{
cout << "Name: " << pr.get_Name() << endl;
cout << "Salary per month: " << pr.perMonth() << endl;
cout << "Salary per year: " << pr.perYear() << endl << endl;
}
}

#include <iostream>
#include <vector>
#include <stdlib.h>
using std::cout;
using std::cin;
using std::endl;
class number
{
private:
std::string name;
float n1_;
int n2_;
public:
number() = default;
~number() = default;
public:
void read();
float perMonth(){return n1_ * n2_;}
float perYear(){return perMonth() * 12;}
std::string get_Name(){return name;}
};
void number::read()
{
cout << "Worker name: "; cin >> name;
n1_ = rand() % 100 + 3;
n2_ = rand() % 100 + 3;
}
int main()
{
int n;
cout << "Insert number of workers:"; cin >> n;
std::vector<number> people(n);
//N.B that pr is a non const reference in this loop
for(number& pr : people){
pr.read();
}
for(number pr : people)
{
cout << "Name: " << pr.get_Name() << endl;
cout << "Salary per month: " << pr.perMonth() << endl;
cout << "Salary per year: " << pr.perYear() << endl << endl;
}
}

Yes, You can put objects into std::vector without using an array.
int main()
{
int n;
cout << "Introduceti numarul de lucratori:"; cin >> n;
std::vector<number> people;
for(int i = 0; i < n; i++)
{
number pers();
pers.read();
people.push_back(per);
}
for(number pr : people)
{
cout << "Name: " << pr.get_Name() << endl;
cout << "Salary per month: " << pr.perMonth() << endl;
cout << "Salary per year: " << pr.perYear() << endl << endl;
}
}

Related

For Loop and Parallel Arrays : Undeclared Identifier

I just started learning about arrays and I have a tenuous grasp on them.
Tried making this program in a lab today and keep getting an error that numJarsSold, typesOfSalsa, and totalJarsSold are undeclared identifiers in MyFunctions.cpp. I've found online already that people have had the same project and seen their code and I've written my own to run just in main but somehow running it separated I've managed to break it. Any help would be appreciated. Thanks.
Main.cpp
#include "MyFunctions.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
const int SIZE = 5;
string typesOfSalsa[SIZE] = { "Mild", "Medium", "Sweet", "Hot", "Zesty" };
int numJarsSold[SIZE]; // Holds Number of Jars of Salsa sold for each type
int totalJarsSold = getJarSalesData(typesOfSalsa, numJarsSold);
displayReport(typesOfSalsa, numJarsSold, totalJarsSold);
system("pause");
return 0;
}
MyFunctions.cpp
#include "MyFunctions.h"
using namespace std;
int getJarSalesData(string typesOfSalsa[], int numJarsSold[])
{
int totalJarsSold = 0;
for (int type = 0; type < SIZE; type++)
{
cout << "Jars sold last month of " << typesOfSalsa[type] << ": ";
cin >> numJarsSold[type];
while (numJarsSold[type] < 0)
{
cout << "Jars sold must be 0 or more. Please re-enter: ";
cin >> numJarsSold[type];
}
// Adds the number of jars sold to the total
totalJarsSold += numJarsSold[type];
}
return totalJarsSold;
}
int posOfLargest(int array[])
{
int indexOfLargest = 0;
for (int pos = 1; pos < SIZE; pos++)
{
if (array[pos] > array[indexOfLargest])
indexOfLargest = pos;
}
return indexOfLargest;
}
int posOfSmallest(int array[])
{
int indexOfSmallest = 0;
for (int pos = 1; pos < SIZE; pos++)
{
if (array[pos] < array[indexOfSmallest])
indexOfSmallest = pos;
}
return indexOfSmallest;
}
void displayReport(string[], int[], int)
{
int hiSalesProduct = posOfLargest(numJarsSold);
int loSalesProduct = posOfSmallest(numJarsSold);
cout << endl << endl;
cout << " Salsa Sales Report \n\n";
cout << "Name Jars Sold \n";
cout << "____________________________\n";
cout << typesOfSalsa[0] << " " << numJarsSold[0] << "\n";
cout << typesOfSalsa[1] << " " << numJarsSold[1] << "\n";
cout << typesOfSalsa[2] << " " << numJarsSold[2] << "\n";
cout << typesOfSalsa[3] << " " << numJarsSold[3] << "\n";
cout << typesOfSalsa[4] << " " << numJarsSold[4] << "\n";
for (int type = 0; type < SIZE; type++)
{
cout << left << setw(25) << typesOfSalsa[type] << setw(10) << numJarsSold[type] << endl;
cout << "\nTotal Sales: " << totalJarsSold << endl;
cout << "High Seller: " << typesOfSalsa[hiSalesProduct] << endl;
cout << "Low Seller: " << typesOfSalsa[loSalesProduct] << endl;
}
}
MyFunctions.h
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int getJarSalesData(string[], int[]);
int posOfLargest(int[]);
int posOfSmallest(int[]);
void displayReport(string[], int[], int);
In MyFunctions.cpp file the function := void displayReport(string[], int[], int) you didn't declared any variable name
it should be like
void displayReport(string typesOfSalsa[], int numJarsSold[], int totalJarsSold)
{
// copy the code
}

Searching through char array

In CPP file #1, I'm trying to loop through the array to see if any of the inputed names match Mordor or the_Vale (from CPP file #2 towards the bottom), however my loop is not working and I only know how to loop through a string array, not a char
#Header File#
#ifndef KINGDOM_H
#define KINGDOM_H
namespace westeros
{
class Kingdom
{
public: //Makes this class public to the rest of the code
char m_name[32];
int m_population;
int count = 0;
};
void display(Kingdom&);
void display(Kingdom* k, int x);
void display(Kingdom* k, int x, int z);
void display(Kingdom* k, int x, char foo[]);
}
#endif
#CPP FIle #1#
#include <iostream>
#include "kingdom.h"
void display(Kingdom* k, int x, char foo[])
{
int a = 0;
int found = 0;
cout << "Searching for kingdom " << foo << " in Westeros" << endl;
for (a; a < x; a++)
{
if (k[a].m_name == foo)
//(strcmp(k[a].m_name) == 0)//Not working
{
cout << k[a].m_name << ", population " << k[a].m_population << endl;
found = 1;
}
}
if (found == 0)
{
cout << foo << " is not part of Westeros." << endl;
}
}
}
## CPP File (main) #2##
#include <iostream>
#include "kingdom.h"
using namespace std;
using namespace westeros;
int main(void)
{
int count = 0; // the number of kingdoms in the array
// TODO: declare the kingdoms pointer here (don't forget to initialize it)
Kingdom* pKingdoms = nullptr;
cout << "==========" << endl
<< "Input data" << endl
<< "==========" << endl
<< "Enter the number of kingdoms: ";
cin >> count;
cin.ignore();
pKingdoms = new Kingdom[count];
for (int i = 0; i < count; ++i)
{
// TODO: add code to accept user input for the kingdoms array
int x = 0;
x++;
cout << "Enter the name for kingdom #" << x + i << ": ";
cin >> pKingdoms[i].m_name;
cout << "Enter the number people living in " << pKingdoms[i].m_name << ": ";
cin >> pKingdoms[i].m_population;
}
cout << "==========" << endl << endl;
// testing that "display(...)" works
cout << "------------------------------" << endl
<< "The first kingdom of Westeros" << endl
<< "------------------------------" << endl;
display(pKingdoms[0]);
cout << "------------------------------" << endl << endl;
// This is where I am having the problem
display(pKingdoms, count, "Mordor");
cout << endl;
display(pKingdoms, count, "The_Vale");
cout << endl;
cout << endl;
delete[] pKingdoms;
pKingdoms = nullptr;
return 0;
}
if (k[a].m_name == foo)
This is not how you compare two C-Style strings. This only compares the pointers, which should result in false almost certainly. You could use strcmp (#include <string.h>):
if (!strcmp(k[a].m_name, foo))
A better way, though, since you're programming in C++, use std::string:
std::string m_name;
and the comparison would have worked flawlessly.

Changing struct into class C++ [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
For my homework assignment, I was supposed to code a struct that collected information about music albums. I was able to do this easily. The second part of my assignment was to turn my struct into a class, and I'm having trouble getting my code to compile. Here are my two codes.
Struct code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
struct Album
{
string name;
string artist;
vector <string> songs;
Date release;
};
void initializeAlbum(Album& a);
void initializeSongs(vector <string> & songs);
void printAlbum(Album a);
int main()
{
Album my_album;
initializeAlbum(my_album);
printAlbum(my_album);
return 0;
}
void initializeAlbum(Album& a)
{
cout << "Enter album name:" << endl;
getline(cin, a.name);
cout << "Enter artist name:" << endl;
getline(cin, a.artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> a.release.month;
cout << "Enter the release day:" << endl;
cin >> a.release.day;
cout << "Enter the release year:" << endl;
cin >> a.release.year;
initializeSongs(a.songs);
}
void initializeSongs(vector <string> & songs)
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void printAlbum(Album a)
{
cout << "The album name is " << a.name << endl;
cout << "The artist name is " << a.artist << endl;
cout << "The release date is " << a.release.day << "/" << a.release.month << "/" << a.release.year << endl;
cout << "The songs are:";
for (int x = 0; x < a.songs.size(); x++ )
cout << " " << a.songs[x] << endl;
}
Class code:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
class Album
{
public:
void printAlbum();
void initializeAlbum();
string name;
string artist;
vector <string> songs;
Date release;
private:
void initializeSongs();
};
int main()
{
Album a;
a.initializeAlbum();
a.printAlbum();
return 0;
}
void Album::initializeAlbum( )
{
cout << "Enter album name:" << endl;
getline(cin, name);
cout << "Enter artist name:" << endl;
getline(cin, artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> release.month;
cout << "Enter the release day:" << endl;
cin >> release.day;
cout << "Enter the release year:" << endl;
cin >> release.year;
initializeSongs(songs);
}
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void Album::printAlbum()
{
cout << "The album name is " << name << endl;
cout << "The artist name is " << artist << endl;
cout << "The release date is " << release.day << "/" << release.month << "/" << release.year << endl;
cout << "The songs are:";
for (int x = 0; x < songs.size(); x++ )
cout << " " << songs[x] << endl;
}
Maybe this line is your error: initializeSongs(songs); in void Album::initializeAlbum() function?
Follow compiler messages.
This function takes zero arguments:
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
Yet you call
initializeSongs(songs);
You can access your members within your class functions so just call it like:
initializeSongs();
This compiles fine:
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct Date
{
int month;
int day;
int year;
};
class Album
{
public:
void printAlbum();
void initializeAlbum();
string name;
string artist;
vector <string> songs;
Date release;
private:
void initializeSongs();
};
int main()
{
Album a;
a.initializeAlbum();
a.printAlbum();
return 0;
}
void Album::initializeAlbum( )
{
cout << "Enter album name:" << endl;
getline(cin, name);
cout << "Enter artist name:" << endl;
getline(cin, artist);
cout << "Enter the release month (numeric format: ex. 06/10/1995):" << endl;
cin >> release.month;
cout << "Enter the release day:" << endl;
cin >> release.day;
cout << "Enter the release year:" << endl;
cin >> release.year;
initializeSongs();
}
void Album::initializeSongs()
{
cout << "How many songs are in the album?" << endl;
int j = 0;
cin >> j;
string answer;
cout << "Enter each song name one at a time:" << endl;
for ( int y = 0; y <= j; y++)
{
getline (cin, answer);
songs.push_back(answer);
}
}
void Album::printAlbum()
{
cout << "The album name is " << name << endl;
cout << "The artist name is " << artist << endl;
cout << "The release date is " << release.day << "/" << release.month << "/" << release.year << endl;
cout << "The songs are:";
for (int x = 0; x < songs.size(); x++ )
cout << " " << songs[x] << endl;
}

How do modify a class so that it has only a single member function with all arguments defaulted?

I'm new to programming (in general) and C++ (in particular) and currently learning classes and objects.
I've defined the following as an exercise:
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
class X
{
public:
void setNum_1(int);
void setNum_2(int);
void setNum_3(int);
void setNum_4(int);
double getNum_1();
double getNum_2(int num_1);
double getNum_3(int num_1, int num_2);
double getNum_4(int num_1, int num_2, int num_3);
private:
int num_1;
int num_2;
int num_3;
int num_4;
};
int main()
{
X testObject;
int lNum_1 = 0;
int lNum_2 = 0;
int lNum_3 = 0;
int lNum_4 = 0;
cout << endl;
cout << "Please enter an integer: ";
cin >> lNum_1;
cout << "Please enter an integer: ";
cin >> lNum_2;
cout << "Please enter an integer: ";
cin >> lNum_3;
cout << "Please enter an integer: ";
cin >> lNum_4;
testObject.setNum_1(lNum_1);
testObject.setNum_2(lNum_2);
testObject.setNum_3(lNum_3);
testObject.setNum_4(lNum_4);
cout << endl;
cout << "The 1st number returned is: " << testObject.getNum_1() << endl;
cout << "The 2nd number returned is: " << testObject.getNum_2(lNum_1) << endl;
cout << "The 3rd number returned is: " << testObject.getNum_3(lNum_1, lNum_2) << endl;
cout << "The 4th number returned is: " << testObject.getNum_4(lNum_1, lNum_2, lNum_3) << endl;
cout << endl;
return 0;
}
void X::setNum_1(int n_1)
{
num_1 = n_1;
}
void X::setNum_2(int n_2)
{
num_2 = n_2;
}
void X::setNum_3(int n_3)
{
num_3 = n_3;
}
void X::setNum_4(int n_4)
{
num_4 = n_4;
}
double X::getNum_1()
{
return sqrt(num_1);
}
double X::getNum_2(int num_1)
{
return pow(num_2,3);
}
double X::getNum_3(int num_1, int num_2)
{
return num_1 * num_2;
}
double X::getNum_4(int num_1, int num_2, int num_3)
{
return (num_1 + num_2) / num_3;
}
Can anyone offer some guidance on how to modify this class so that it has only one member function with all of the arguments defaulted?
Thanks in advance,
Ryan
Ofcourse there are MANY ways to do this and most of them will be more elegant than what I have done here. But this should give you some ideas.
a. You should use the variables defined in the class
b. If you need to perform certain conditional operations in a function, use a switch case or an if statement. And decide the operation based on a parameter passed.
Again, many ways to make this more elegant, but this should get you started and thinking.
#include "stdafx.h"
#include <iostream>
#include <cmath>
using namespace std;
class X
{
public:
void setNums(int, int, int, int);
double performOp(int);
private:
int num_1;
int num_2;
int num_3;
int num_4;
};
int main()
{
X testObject;
int lNum_1 = 0;
int lNum_2 = 0;
int lNum_3 = 0;
int lNum_4 = 0;
cout << endl;
cout << "Please enter an integer: ";
cin >> lNum_1;
cout << "Please enter an integer: ";
cin >> lNum_2;
cout << "Please enter an integer: ";
cin >> lNum_3;
cout << "Please enter an integer: ";
cin >> lNum_4;
testObject.setNums(lNum_1,lNum_2,lNum_3,lNum_4);
cout << endl;
cout << "The 1st number returned is: " << testObject.performOp(1) << endl;
cout << "The 2nd number returned is: " << testObject.performOp(2) << endl;
cout << "The 3rd number returned is: " << testObject.performOp(3) << endl;
cout << "The 4th number returned is: " << testObject.performOp(4) << endl;
cout << endl;
return 0;
}
void X::setNums(int n_1, int n_2, int n_3, int n_4)
{
num_1 = n_1;
num_2 = n_2;
num_3 = n_3;
num_4 = n_4;
}
double X::performOp(int n)
{
if(n == 1) return sqrt(num_1);
if(n == 2) return pow(num_2,3);
if(n == 3) return num_1 * num_2;
if(n == 4) return (num_1 + num_2) / num_3;
}

How to add a name field for a shop database (OOP/C++)

Ok, so I've made a database type program and created an item number and price field. I've also tried to stick to a primary key by using the index values of the array of both the "item number" field and "price". But was wondering how to add an "Item name" field along with this to make it work. I've tried to think of many different ways of adding a char type array but that doesn't really work.
#include<iostream>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
void main()
{
class shop s;
s.input();
s.output();
}
Create a class or struct to hold the data:
struct Item
{
int id;
float price; // float may lead to rounding errors.
// I would use int and store cents
//string name;
// If you really want to use c-style string
char name[20];
// or
// char *name; // You would need to use new with this
};
Then keep an array of these:
class shop
{
private:
Item items[20];
// As mentioned, better than a static array would be a vector
//std::vector<Item> items;
public:
void input();
void output();
};
What about a vector of strings?
#include<iostream>
#include <string>
#include <vector>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
vector<string> names;
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
names.resize(n);
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the price of the item: ";
cin >> price[i];
cout << "Enter the name of the item: ";
cin >> names[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Price: " << price[i] << endl << endl;
cout << "Name: " << names[i] << endl << endl;
}
}
And it would be good to have a destructor to clean the memory taken by the vector.
I would use std::string
#include <iostream>
#include <string>
using namespace std;
class shop
{
private:
int i,n, item[20];
float price[20];
string name[20];
public:
void input();
void output();
};
void shop::input()
{
cout<<"Enter the number of items: ";
cin>>n;
for (i = 1; i <= n; i++)
{
cout << "Enter the item number of the " << i << " item: ";
cin >> item[i];
cout << "Enter the name of the item: ";
cin >> name[i];
cout << "Enter the price of the item: ";
cin >> price[i];
}
}
void shop::output()
{
for (i = 1; i <= n; i++)
{
cout << "Item Number: " << item[i] << endl;
cout << "Item Name: " << name[i] << endl;
cout << "Price: " << price[i] << endl << endl;
}
}
int main()
{
class shop s;
s.input();
s.output();
}