Sorting multiple linked arrays in C++ [duplicate] - c++

This question already has answers here:
Sorting two corresponding arrays [duplicate]
(4 answers)
Closed 6 years ago.
Consider the following list:
Name Price(per kg) Weight(in kg)
rice1 40 20
rice2 50 27
rice3 35 24
I want all the rice types sorted according to their value. So, I sort them.
new sorted price: 35 40 50
Now i print them and the output as below:
Name Price Weight
rice1 35 20
rice2 40 27
rice3 50 24
But this is not what I wanted. I wanted it to print like this:
Name Price Weight
rice3 35 24
rice1 40 20
rice2 50 27
so, the problem is I'm getting the the value in the sorted list but not the names and weights. I want to get sorted everything according to value.
How can i do that?
I've written the following code. But not sure what to do next.
#include <iostream>
#include <string>
#include <algorithm>
int main()
{
class treasure
{
public:
std::string name[100];
double value[100];
double weight[100];
};
int itemNumber, totalWeight, i;
treasure item;
std::cout << "Enter total item weight(in kg): " << std::endl;
std::cin >> totalWeight;
std::cout << std::endl <<"Enter total item number: " << std::endl;
std::cin >> itemNumber;
//take item name, item value, item weight
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << "Enter item name: " << "\t" << "Enter item value(per kg): " << "\t" << "Enter item weight(in kg): " << std::endl;
std::cin >> item.name[i] >> item.value[i] >> item.weight[i];
}
//sort items according to given value
std::sort(item.value, item.value + itemNumber);
//print sorted list
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << std::endl << "Item name: " << "\t" << "Item value(per kg): " << "\t" << "Item weight(in kg): " << std::endl;
std::cout << item.name[i] << "\t\t" << item.value[i] << "\t\t\t" << item.weight[i] << std::endl;
}
return 0;
}

Your structure should look like this:
class treasure
{
public:
std::string name;
double value;
double weight;
};
and then you declare array of treasures:
treasure item[100];
taking items:
//take item name, item value, item weight
for( i = 0; i < itemNumber; i++)
{
std::cout << std::endl << "Enter item name: " << "\t" << "Enter item value(per kg): " << "\t" << "Enter item weight(in kg): " << std::endl;
std::cin >> item[i].name >> item[i].value >> item[i].weight;
}
and finally sorting:
std::sort(item, item + itemNumber,
[] (auto t1, auto t2) {return t1.value < t2.value;})
http://ideone.com/GL3VKz

Related

How can I add horizontal space between two functions in C++?

So I want to output a list of the names and randomly generated numbers. I already did everything else it is just that I do not know how to output it the way I want it to.
I want it to output like this:
ID #: Names:
1 bob
23 rob
44 kanye
Here is what I have so far:
cout << "Would you like to view the archived names and IDs? (Y/N)" << endl;
string archiveInput;
cin >> archiveInput;
if(tolower(archiveInput[0]) == 'y')
{
cout << "ID #: Names: " << endl;
output(ids, names);
}
Here are my functions I used.
void output(const vector<int>& ids)
{
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << endl;
}
cout << endl;
}
void output(const vector<string>& names)
{
for(int i = 0; i < names.size(); i++)
{
cout << names[i] << endl; //might have to use endl for list format
}
cout << endl;
}
void output(const vector<int>& ids, const vector<string>& names)
{
cout << output(ids) << " " << output(names); //I thought this would work, im new :(
}
Try to using this method
#include <iostream>
#include <iomanip>
using namespace std;
class Student
{
public:
string studentName;
int studentAge;
int studentMarks;
int admissionYear;
Student(string name, int age, int marks, int year)
{
studentName = name;
studentAge = age;
studentMarks = marks;
admissionYear = year;
}
};
int main()
{
Student studentArray[4] = {Student("Alex", 20, 80, 2018), Student("Bob", 21, 82, 2018), Student("Chandler", 23, 85, 2017), Student("Rose", 18, 89, 2019)};
cout
<< left
<< setw(10)
<< "Name"
<< left
<< setw(5)
<< "Age"
<< left
<< setw(8)
<< "Marks"
<< left
<< setw(5)
<< "Year"
<< endl;
for (int i = 0; i < 4; i++)
{
cout
<< left
<< setw(10)
<< studentArray[i].studentName
<< left
<< setw(5)
<< studentArray[i].studentAge
<< left
<< setw(8)
<< studentArray[i].studentMarks
<< left
<< setw(5)
<< studentArray[i].admissionYear
<< endl;
}
return 0;
}
It will print the below output :
Name Age Marks Year
Alex 20 80 2018
Bob 21 82 2018
Chandler 23 85 2017
Rose 18 89 2019
We have set different widths for each column. The first column width is 10, the second column width is 5, the third column width is 8, and the last column width is 5.
The width is important here. If it is less than the size of its content, the content will overflow.
cout << output(ids) << " " << output(names);
First runs the function output overloaded with ids argument, and afterwards runs the version with the names like so:
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << endl;
}
cout << endl;
// returns from first function call
cout << " ";
// enters second function call
for(int i = 0; i < names.size(); i++)
{
cout << names[i] << endl; //might have to use endl for list format
}
cout << endl;
Is how the compiler will run it, which is why your output is underneath each other.
This code is what you want inside the overload with the two arguments:
for(int i = 0; i < ids.size(); i++)
{
cout << ids[i] << " " << names[i] << endl;
}
cout << endl;
However your output will still not quite look like how you want. You have to apply other tricks for that.
This is the reason why your current code behave like that. Look at M Khaidar's answer for the correct way to solve your problem.

Loop isn't printing expected results

I'm trying to prompt the user for items and the quantity of those items respectively. But when I run the program, it correctly displays the elements in the first vector, and not the elements in the second vector.
#include <iostream>
#include <vector>
using namespace std;
int main(){
// Declaring vectors
vector <string> items{};
vector <int> quantity{};
cout << "Enter name of items." << endl;
// Read input to vectors
for(int i{1}; i <= 3; ++i){
string item{};
cin >> item;
items.push_back(item);
}
cout << "Enter quantity of each item." << endl;
for(int i{1}; i <= 3; ++i){
int num{};
cin >> num;
quantity.push_back(num);
}
// Display data
for(auto item: items){
int i{0};
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}
return 0;
}
output
Enter name of items.
meat fish milk
Enter quantity of each item.
10 20 30
Item: meat - Quantity: 10
--------------------
Item: fish - Quantity: 10
--------------------
Item: milk - Quantity: 10
--------------------
I tried printing out quantity.at(1) and it correctly displays 20, I apologize in advance if I missed out on something obvious. I'm very new to the language.
You are always setting i equal to the 0th element. instead move the creation of i to be outside the loop:
int i{0};
for(auto item: items){
cout << "Item: " << item << " - " << "Quantity: " << quantity.at(i) << endl;
++i;
cout << "--------------------" << endl;
}
You can fix it by bringing the "i" variable out of the last iteration

C++ class loop in main

I need help in a simple way of solving a part of my code that i cant seem to make it work.The point of my "assignment" is that everything must try to be in one class.Now the problem i am having is at a part of my code where it is suppose to "print" the n number of products meaning that it displays what you have inputted in the void get() part,but the problem i cant seem to resolve is it only prints the last name,amount,weight of the product and not everything written.
class Class
{
public:
string name;
int n, amount;
float weight;
void market()
{
cout << "Give the number of products you want to get at Market : " << endl;
cin >> n;
}
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name >> amount >> weight;
}
}
void print()
{
cout << "\nProduct display:\n" << endl;
for (int i = 0; i < n; i++)
{
cout << name << " - " << amount << " , " << weight << " kg" << endl;
cout << "------------------------" << endl;
}
};
};
The main part.
int main()
{
Class market;
market.market();
market.get();
market.print();
}
You're actually overwriting name, amount and weight. You have to make use of something similar to std::vector:
class Class {
public:
std::vector<string> names;
// Same for others
When you get them from std::cin you have to push them into the vector:
names.push_back(name);
amounts.push_back(amount);
weights.push_back(weight);
When printing you loop over the vectors:
for (int i = 0; i < n; i++) {
cout << names[i] << " - " << amounts[i] << " , " << weights[i] << " kg" << endl;
cout << "------------------------" << endl;
}
You must use a std::vector<TYPE> (example 1), or array for holding multiple data in a single variable (example 2).
Example 1
Since you've been coding in C++ programming language, it's highly recommended to use std::vector<> for best results.
Consider the class example (read comments too):
int count = 0; // PRIVATE SECTION
char ask;
std::vector<std::string> name;
std::vector<int> amount;
std::vector<float> weight;
std::string tName; // temp variables
int tAmount;
float tWeight;
public:
void market()
{
cout << "WELCOME!" << endl; // nothing's required with vector
}
void get()
{
do {
cout << "Give product name, amount and weight : " << endl;
cin >> tName >> tAmount >> tWeight; // getting temporary variables
name.push_back(tName); // assigning
amount.push_back(tAmount);
weight.push_back(tWeight);
count++;
cout << "Add more? (Y/n): "; // add more? Go on if yes...
cin >> ask;
} while (ask == 'Y' || ask == 'y');
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < count; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
WELCOME!
Give product name, amount and weight :
ABC 12 55.5
Add more? (Y/n): y
Give product name, amount and weight :
SSD 33 43.2
Add more? (Y/n): n
Product display:
ABC - 12 , 55.5 kg
------------------------
SSD - 33 , 43.2 kg
------------------------
Example 2
You can do the same thing just with few modifications, but having static number isn't considered dynamic. You can use arrays for your program as stated below.
Rather than:
string name;
int n, amount;
float weight;
Consider const int MAX = 1024; and use (class variables must be visible only inner the class and nowhere else):
private: // declare on top of the class ("private:" is by default and redundant)
string name[MAX];
int n, amount[MAX];
float weight[MAX];
Edited & working example class:
void get()
{
for (int i = 0; i < n; i++)
{
cout << "Give product name,amount and weight : " << endl;
cin >> name[i] >> amount[i] >> weight[i];
}
}
void print()
{
cout << "\nProduct display:\n"
<< endl;
for (int i = 0; i < n; i++)
{
cout << name[i] << " - " << amount[i] << " , " << weight[i] << " kg" << endl;
cout << "------------------------" << endl;
}
}
Sample Output
Give the number of products you want to get at Market :
2
Give product name,amount and weight :
ABC 25 102
Give product name,amount and weight :
BDE 22 333
Product display:
ABC - 25 , 102 kg
------------------------
BDE - 22 , 333 kg
------------------------

How can I display only cars with 5 seats?

How can I make the program display only cars that have 5 seats, for now no matter what, it shows all cars that I write infos about them, for example if I write in the console that there are 3 cars and give information about them and say that one has 2 seats and the others have 5 after I run the program it still displays all 3 of them. Any idea of how can I display only cars with 5 seats? Can I somehow use the quicksort() function ?
#include <iostream>
using namespace std;
struct Car
{
int no_seats;
int year;
char brand[20];
char color[20];
float horse_power;
};
void read_cars(Car C[], int &n)
{
int i;
cout << "Number of parked cars "; cin >> n;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cin >> M[i].brand;
cout << "The year it was made in " ; cin >> M[i].year;
cout << "Color " ; cin >> M[i].color;
cout << "Power " ; cin >> M[i].horse_power;
cout << "Number of seats " ; cin >> M[i].no_seats;
}
}
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
int main()
{
Car C[50];
int n;
read_cars(M, n);
display_cars(M, n);
return 0;
}
You need to add a condition in the loop:
void display_cars(Car C[], int n)
{
int i;
for(i=1; i<=n; i++)
{
if(M[i].no_seats == 5) // <- like this
{
cout << "Brand " ; cout << M[i].brand << endl;
cout << "The year it was made in " ; cout << M[i].year << endl;
cout << "Color " ; cout << M[i].color << endl;
cout << "Power " ; cout << M[i].horse_power << endl;
cout << "Number of seats " ; cout << M[i].no_seats << endl;
}
}
}
Other notes:
Your n can only go up to 49 - remember that. That also means that you are wasting an element at M[0] (yes arrays are zero based in C++).
Prefer to use std::vector<Car> C over an array of fixed size. A std::vector grows as you push_back more and more elements into it - and it keeps track of the number of contained elements, so you do not need to pass the size of the vector around. C.size() would tell you the number of elements.
void display_cars(const std::vector<Car>& C)
{
std::cout << "There are " << C.size() << " cars in the vector\n";
for(const Car& a_car : C) // a range based for-loop
{
if(a_car.no_seats == 5) // a_car will be a reference to each car in the loop
{
// use "a_car" to display info about one particular car
}
}
}

Formatting output (inputted by the user) in columns

I am working on a shopping cart project, and I want to print out the user input like the following output. I don't know how to use setW and right/left keywords, when it comes to the user decides what the output is going to be like. So when they enter different inputs in length, for example setW(20) does not work for them all.
Here is your order:
----------------------------------------------------------------
Name Unit_Price Quantity
T-shirt $19.99 2
Sweater $39.99 1
iphone_case $25.5 3
Towel $9.99 5
The total charge is $206.42
----------------------------------------------------------------
This is the display function:
ostream& operator <<(ostream& os, Item& source) {
os << source.getName() << setw(18)
<< source.getPrice() << setw(20) << source.getQuantity() << endl;
return os;
}
And this is the output I get with this:
Here is your order:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
The total price of the order is 206.42
----------------------------------------
And here is my main.cpp
#include "ShoppingCart.h"
#include "Item.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
cout << endl << endl << "Welcome to XXX SHOPPING CENTER" << endl;
Item items[10];
ShoppingCart<Item> cart;
char userAnswer;
cout << "Enter the item you selected as the following order:\nname unitPrice quantity\n"
<< "(Name can not contain any space. Otherwise errors happen!)" << endl;
cin >> items[0];
cart.add(items[0]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
int index = 1;
while(userAnswer == 'y' || userAnswer == 'Y') {
cout << "Enter the next item:" << endl;
cin >> items[index];
cart.add(items[index]);
cout << "Want to continue? y/n" << endl;
cin >> userAnswer;
index++;
}
// Display the summary of the orders
cout << endl << "Here is your order:" << endl;
// "--------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl << "NAME" << setw(18) << "PRICE" << setw(20) << "QUANTITY" << endl;
for(int i=0; i < cart.getCurrentSize(); i++) {
cout << items[i];
}
cout << endl << "The total price of the order is " << cart.getTotalPrice() << endl;
// "---------------------------------------------------------------------"
for(int i=0; i < 40; i++)
cout << "-";
cout << endl;
return 0;
}
The strategy you are using does not make sense to me. Here's one way to get the desired output:
Use 20 characters for the first column and make sure that it is output with left aligned text.
Use 10 characters for the second and third columns, and make sure they are output with right aligned text.
Use std::left and std::right to control text alignment.
Here's a simplified program that demonstrates the idea.
#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
struct Item
{
std::string name;
double price;
int quantity;
};
std::ostream& operator<<(std::ostream& out, Item const& item)
{
// First column
out << std::left << std::setw(20) << item.name;
// Second and third columns
out << std::right << std::setw(10) << item.price << std::setw(10) << item.quantity;
return out;
}
void printLine(std::ostream& out)
{
for(int i=0; i < 40; i++)
out << "-";
out << std::endl;
}
int main()
{
std::vector<Item> items;
items.push_back({"tshirt", 19.99, 2});
items.push_back({"sweater", 39.99, 1});
items.push_back({"iphone_case", 25.50, 3});
items.push_back({"towel", 9.99, 5});
printLine(std::cout);
// First column
std::cout << std::left << std::setw(20) << "NAME"
// Second and third columns
std::cout << std::right << std::setw(10) << "PRICE" << std::setw(10) << "QUANTITY" << std::endl;
// The items
for(int i=0; i < 4; i++) {
std::cout << items[i] << std::endl;
}
printLine(std::cout);
}
Output:
----------------------------------------
NAME PRICE QUANTITY
tshirt 19.99 2
sweater 39.99 1
iphone_case 25.5 3
towel 9.99 5
----------------------------------------