I'm a newbie and this is my first question. So I am working for a task organizer and I want to organize list of tasks by their "urgency" value. Here is my code:
#include <iostream>
#include <math.h>
#include <vector>
#include <stdlib.h>
#include <list>
using namespace std;
struct Task {
public:
string name;
float deadline, estimated;
int urgency;
int getUrgency() {
urgency = ceil(deadline - estimated);
return urgency;
}
};
void newTask(Task task[], int n1) {
for (int i = 0; i < n1; i++)
{
system("cls");
cout << "Input task name: ";
cin >> task[i].name;
cout << "Input task deadline (in hours): ";
cin >> task[i].deadline;
cout << "Input task estimated work time (in hours): ";
cin >> task[i].estimated;
}
}
void printAll(Task task[], int n1) {
system("cls");
cout << "Name\tDeadline\tEstimated\tUrgency\n";
for (int i = 0; i < n1; i++)
{
cout << task[i].name << "\t" << task[i].deadline << "\t\t" << task[i].estimated << "\t\t" << task[i].getUrgency() << endl;
}
}
int main() {
int n;
cout << "How many work do you have? ";
cin >> n;
//Create number of object based on input n
std::vector<Task> p(n);
newTask(p.data(), n);
std::list<Task> taskList;
printAll(p.data(), n);
cin.ignore();
return 0;
}
I want to add a function that sorts the list of tasks by their "urgency" value. What kind of function should I use?
In your case you can use the std::sort function, defined in <algorithm> header, on the p vector defining a custom compare function:
std::sort (p.begin(), p.end(), sortTaskByUrgency);
where sortTaskByUrgency() is defined as:
bool sortTaskByUrgency(const Task& lhs, const Task& rhs)
{
return lhs.getUrgency() < rhs.getUrgency();
}
Using the above function in your sample code getUrgency() must be const:
int getUrgency() const { return ceil(deadline - estimated); }
removing useless int urgency public member.
I would try using std::sort. It will sort in place any iterable object (array, vector, etc...). A common std::sort function call has the following arguments: The first argument is an iterator/pointer to the beginning of the collection, the second argument is an iterator/pointer to the end of that same collection, and the third argument is a function callback that determines how the data is sorted. You can see an example implementation here
Related
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
struct StudentDataTypes
{
std::string name{};
int grade{};
};
int main()
{
//Ask for Class_Size
int Class_Size{};
std::cout << "How big is the class?" << '\n';
std::cin >> Class_Size;
//Syntax format
//std::vector<T> array(size);
//Intialize a vector for the students called Vector_Student
//T links to the struct StudentDataTypes
//size is the Class_Size.
std::vector<StudentDataTypes> Vector_Student(Class_Size);
//Print Class Size
std::cout << "There are " << Class_Size << " students." << '\n';
//Get the Userinputs for the Class
for (int i = 0; i < Class_Size; ++i)
{
std::cout << "Please input the name of Student #" << i + 1 << '\n';
std::cin >> Vector_Student[i].name;
std::cout << "Please input the grade of Student #" << i + 1 << '\n';
std::cin >> Vector_Student[i].grade;
}
//Sort
std::sort(Vector_Student.begin(), Vector_Student.end());
//Print the required output
for (int j = 0; j < Class_Size; ++j)
{
std::cout
<< Vector_Student[j].name
<< " got a grade of "
<< Vector_Student[j].grade << '\n';
}
return 0;
}
I have an issue with a Vector Struct tutorial.
I'm using Visual Studio 2019 and there's a peculiar scenario where the compiler doesn't give me any warning at all. If I debug it, the first warning appears on line 1544, way out of bounds. The above code will actually sort of compile, run and crash.
I know the issue lies in the sorting but I can't figure it out.
std::sort requires you to implement operator< for your datatype. Here in this case adding following definition in your class will get your code to compile
bool operator<(const StudentDataTypes& that) {
return this->grade < that.grade;
}
Update:
Alternatively as sugested by Casey, we can use custom sort comparator. Here is the sample code for the same.
std::sort(Vector_Student.begin(), Vector_Student.end(), [](const StudentDataTypes& a, const StudentDataTypes&b) { return a.grade < b.grade; });
Here is the answer. I'm posting it in the answers for how to sort a vector-struct.
Step 1:
bool compareTwoStudents(StudentDataTypes a, StudentDataTypes b) {
if (a.grade != b.grade)
return a.grade > b.grade;
return a.grade==b.grade;
}
Step 2:
std::sort(Vector_Student.begin(), Vector_Student.end(),compareTwoStudents);
I am a beginner in programming.I have a problem. I am trying to code the Enigma machine. I have two classes. One for Enigma, one for rotors. Rotors are small parts of the enigma machine, that doesn't matter for the problem. My problem is the error. I cannot cout, the function cout << rotors[0].GetRotor(); which should return my vector of integers. I have no idea why is that. I don't need that to my program, but I'm not sure if my adding rotor to enigma void AddRotor(Rotor rotor) { rotors.push_back(rotor); }function, called in "TakeRotors" function, works right. In my opinion, it should work well, but I can't check it. Debugger, unfortunately, doesn't show any values of vector<Rotor> rotors; permutation so I am not sure :( Any help would be great. Thank You.
Here's my full, needed code :)
#include <iostream>
#include <vector>
using namespace std;
class Rotor {
public:
vector <int> permutation;
int position;
Rotor(vector<int> permutation) {
position = 0;
permutation;
}
vector<int> GetRotor() const {
return permutation;
}
};
class Enigma {
public:
vector<Rotor> rotors;
void AddRotor(Rotor rotor) {
rotors.push_back(rotor);
}
void PrintRotor(const vector<Rotor>& rotors) {
cout << rotors[0].GetRotor(); // Error right here
cout << rotors[0].position;
}
void setupRotor(int index) {
Rotor rotor = rotors[index];
}
void MoveRotor(int index) {
rotors[index].position++;
cout << "Before" << endl;
// cout << rotors[index].permutation.data << ' ';
Enigma::PrintRotor(rotors);
rotate(rotors[index].permutation.begin(), rotors[index].permutation.begin() + rotors[index].permutation.size(), rotors[index].permutation.end());
cout << "After" << endl;
Enigma::PrintRotor(rotors);
}
};
vector<int> take_numbers(int number) {
vector<int> numbers;
for (int i = 0; i < number; i++) {
int number;
cin >> number;
numbers.push_back(number);
}
return numbers;
}
void take_rotors(int number_letters, Enigma* enigma) {
int numberOfRotors;
// int numberOfNotch, positionOfNotch;
cout << "Give number of Rotors" << endl;
cin >> numberOfRotors;
for (int i=0; i < numberOfRotors; i++) {
vector<int> permutation = take_numbers(number_letters);
Rotor Rotor(permutation);
enigma->AddRotor(Rotor); // I am not sure if it adds Rotors fine.
}
}
int main()
{
Enigma enigma;
int number_letters, move_rotor;
cout << "Give number of letters in alphabet" << endl;
cin >> number_letters;
take_rotors(number_letters, &enigma);
// take_reflectors(number_letters, &enigma);
cout << "Which rotor do you want to move (index)" << endl;
cin >> move_rotor;
enigma.MoveRotor(move_rotor);
return 0;
}
There is no operator<<(std::ostream&,const std::vector<int>&) if you want it you need to supply your own. However, overloading operators for types you don't own is not recommended, so I would rather write a function:
void print_vector(std::ostream& out, const std::vector<int>& vect) {
for (int i : vect) {
out << i << '\n';
}
}
That you can call like this
print_vector(std::cout, rotors[0].GetRotor());
Alternatively you can supply an overload for << that prints all the Rotor:
std::ostream& operator<<(std::ostream&,const Rotor& rotor) {
out << rotor.position;
for (auto& i : rotor.GetRotor()) {
out << i;
}
// modify and add more to your likings
return out;
}
Once you have that you can also provide an overload to print a vector of rotors that you can use in Enigma::PrintRotor (which currently only prints the first element of the vector):
std::ostream& operator<<(std::ostream& out,const std::vector<Rotor>& rotors) {
for (const auto& r : rotors) {
out << r << '\n';
}
return out;
}
PS your naming is a little confusing. A Rotor has a GetRotor which returns permutations !?! I strongly suggest to use better names. If I have Rotor r; then r is the Rotor and it is not obvious what a GetRotor will do. Maybe rename it to GetPermutations?
I extremely need to pass data types to the constructor of classes. I’m working on image processing (till now in Matlab) and now need to use ITK and VTK libraries. In fact, my images are coming from different types and sizes. Unfortunately, I don’t know how to pass a data type to my classes. It’s really painful to have different copies of same classes with different data types!!!
Here is a very simple example to express what I mean and need. In this example, I’m going to create a dynamic array of “int” type. This exaple works well but I don't know how to employ templates. Could you please let me know how I can change the code to be able define any type of dynamic array?
Thanks in advance,
Main
#include "stdafx.h"
#include <iostream>
#include <string>
#include "Myclass.h"
using namespace std;
int main()
{
Myclass c1;
system("pause");
return 0;
}
Class definition:
Myclass.h
class Myclass
{
public:
Myclass();
~Myclass();
private:
int size;
int* my_dynamic_array;
void SetPrivate();
};
Myclass.cpp
#include "stdafx.h"
#include "Myclass.h"
#include <iostream>
using namespace std;
Myclass::Myclass()
{
cout << "Please enter the size of array: ";
cin >> size;
my_dynamic_array = new int[size];
SetPrivate();
}
void Myclass::SetPrivate() {
cout << "\n\nPlease enter " << size << " numbers for the array elements...";
for (int i = 0; i < size; i++) {
cout << "\n\n#" <<i+1<<" : ";
cin >> my_dynamic_array[i];
}
}
Myclass::~Myclass()
{
delete[] my_dynamic_array;
}
Not commenting on whether you could use vector instead of int *my_dynamic_array, I just translated your code into a template. Hope it helps somehow:
template<typename T>
class ImageClass {
public:
ImageClass<T>() {
cout << "Please enter the size of array: ";
cin >> this->size;
my_dynamic_array = new T[this->size];
SetPrivate();
}
void SetPrivate() {
cout << "\n\nPlease enter " << this->size << " numbers for the array elements...";
for (int i = 0; i < this->size; i++) {
cout << "\n\n#" <<i+1<<" : ";
cin >> my_dynamic_array[i];
}
}
protected:
int size;
T *my_dynamic_array;
};
int main() {
ImageClass<int> ic_i;
ImageClass<double> ic_d;
}
I got a program to create in C++ in our introduction to C++ class in school. I am doing everything as I got in examples, but still getting errors.
w4x.cpp was given and I have to create Molecule.h and Molecule.cpp. I did that, but I am getting errors because my variables were not declared in scope, but I can't understand why.
// w4x.cpp
#include <iostream>
using namespace std;
#include "w4x.h"
#include "Molecule.h"
int main() {
int n = MAX_MOLECULES;
Molecule molecule[MAX_MOLECULES];
cout << "Molecular Information\n";
cout << "=====================" << endl;
for (int i = 0; i < MAX_MOLECULES; i++) {
if (!molecule[i].read()) {
n = i;
i = MAX_MOLECULES;
}
cout << endl;
}
cout << "Structure Name Mass\n";
cout << "==================================================" << endl;
for (int i = 0; i < n; i++)
molecule[i].display();
}
//Molecule.h
const int MAX_STRUCT = 10;
const int MAX_NAME = 20;
class Molecule {
char name[MAX_STRUCT];
char rate[MAX_NAME];
double weight;
public:
Molecule();
void read(const char*, const char*, double);
void display() const;
~Molecule();
};
//Molecule.cpp
#include <iostream>
#include <cstring>
using namespace std;
#include "Molecule.h"
Molecule::Molecule(){
name[0]= '\0';
rate[0]= '\0';
weight = 0;
}
void::read(const char* n, const char* r, double w) {
weight = w;
strncpy (name, n, MAX_STRUCT);
name[MAX_STRUCT]='\0';
strncpy (rate, r, MAX_NAME);
rate[MAX_NAME]='\0';
cout << "Enter structure : ";
cin.getline (n, MAX_CHARS);
cout << "Enter full name : ";
cin.getline (r, MAX_NAME);
cout << "Enter weight : ";
cin >> w;
}
void::display() const
{
int x;
for ( x=0; x<i; x++)
cout << n << " " << r << " " << w << endl;
}
My first question is, how can I pass char name[MAX_STRUCT]; char rate[MAX_NAME]; double weight; from Molecule.h to Molecule.cpp
The problem with your definitions is here:
void::read(const char* n, const char* r, double w)
and here
void::display() const
What :: says here, is that you are implementing a function within a class. So you need to specify which class and which function! What you are telling it now, is that you are implementing a function inside class void, which is nonexistent.
You should convert them to:
void Molecule::read(const char* n, const char* r, double w)
void Molecule::display() const
Your other question regarding passing class members:
The functions of a class have access to its variables, therefore, you don't need to concern yourself with that. Just use the variables.
Also, if you notice in your w4x.cpp, the function Molecule::read() is called without parameters, so your TAs ask you to implement it without parameters. Indeed, since you have access to Molecule::name, Molecule::rate and Molecule::weight directly, you should read data and write to those variables instead of asking for parameters. Therefore, your read function would look like this:
void Molecule::read()
{
// read into name, rate and weight
}
Furthermore, w4x.cpp expects read to report whether it has been successful or not. This means that you should do error checking in Molecule::read and return 0 if no errors or -1 (for example) in case of errors.
I wounder how i can make this code work?
#include <iostream>
using namespace std;
void writeTable(int (&tab)[],int x){
for(int i=0;i<x;i++){
cout << "Enter value " << i+1 <<endl;
cin >> tab[i] ;
}
}
int main(void){
int howMany;
cout << "How many elemets" << endl;
cin >> howMany;
int table[howMany];
int (&ref)[howMany]=table;
writeTable(ref,howMany);
return 0;
}
And here are the errors that I have:
|4|error: parameter ‘tab’ includes reference to array of unknown bound ‘int []’|
|18|error: invalid initialization of reference of type ‘int (&)[]’ from expression of type ‘int [(((unsigned int)(((int)howMany) + -0x00000000000000001)) + 1)]’|
|4|error: in passing argument 1 of ‘void writeTable(int (&)[], int)’|
Thanks for help
If you are intending to pass the size of the array, then remove the reference
void f(int a[])
is equivalent to
void f(int* a)
so no copying will be done, if that is the concern.
If you want to take an array by reference, then you MUST specify the dimension. e.g.
void f(int (&a)[10])
Naturally, the best of the two is the third solution, which is to use std::vector's and pass them by reference, reference to const or by value if needed. HTH
Here is a slightly more C++ style of doing it:
#include <iostream>
#include <vector>
void writeTable(std::vector<int> &tab)
{
int val;
for (unsigned int i=0; i<tab.size(); i++)
{
std::cout << "Enter value " << i+1 << std::endl;
if (std::cin >> val)
{
tab[i] = val;
}
}
}
int main()
{
int howMany;
std::cout << "How many elements?" << std::endl;
std::cin >> howMany;
std::vector<int> table(howMany);
writeTable(table);
return 0;
}
You need not specify the dimension of the array if you make writeTable a function template.
template <typename T,size_t N>
void writeTable(T (&tab)[N]) //Template argument deduction
{
for(int i=0 ; i<N ; i++){
// code ....
}
}
.
int table[howMany]; // C++ doesn't have Variable Length Arrays. `howMany` must be a constant
writeTable(table); // type and size of `table` is automatically deduced
Following Amardeep's answer, here is a C++11 way to do it:
#include <iostream>
#include <vector>
void writeTable(std::vector<int> &tab)
{
int val;
for (auto& cell : tab)
{
std::cout << "Enter value " << i+1 << std::endl;
if (std::cin >> val)
{
cell = val;
}
}
}
int main()
{
int howMany;
std::cout << "How many elements?" << std::endl;
std::cin >> howMany;
std::vector<int> table(howMany);
writeTable(table);
return 0;
}
Note the range-based for used in writeTable.
Arrays of references are illegal, if that is what you are trying to do. It's not 100% clear to me from the title.