Is this kind of implementation of nested linked list valid in c++?
if yes,then how to declare a head to those nested linked lists?
what is the syntax for accessing the data in those lists inside?
here is a part of my general code.
I'm trying to perform a library management system in c++.
struct course
{
string course_name;
struct course_books
{
struct wait_list
{
long stu_num;
//date inserted
wait_list * next_wait_stu;
};
struct voters_list
{
long stu_num;
int vote;
voters_list * next_voter;
};
struct deposit_list
{
long stu_num;
//date given
//bring back date
deposit_list * next_depositor;
};
};
course * next_course;
};
struct demand
{
int ISBN;
string book_name,
course,
author,
edition;
int demands_num;
struct demanding_students
{
string demander_name;
int demander_stu_number;
//demand date
demanding_students * next_demanding_stu;
};
demand * next_demand;
};
struct STUDENT_INFO
{
struct all_deposited_books
{
int ISBN;
//date given
//bring back date
all_deposited_books * next_dep_book;
};
struct today_deposited
{
int ISBN;
today_deposited * next_today_dep_book;
};
};
You would probably want to use classes for this instead. Something like:
class STUDENT_INFO{
protected:
struct all_deposited_books
{
int ISBN;
//date given
//bring back date
};
struct today_deposited
{
int ISBN;
};
public:
all_deposited_books * next_dep_book;
today_deposited * next_today_dep_book;
};
Then you create a class instance like: STUDENT_INFO theBestStudentInfo; and if you want to accses a struct variable inside that you just call: theBestStudentInfo.all_deposited_books[0].ISBN = 5; or something like that.
Aswell as I dont think you can create a struct instance inside the struct itself, like:
struct all_deposited_books
{
int ISBN;
//date given
//bring back date
all_deposited_books * next_dep_book; //<- this is probably gonna cause problems
};
first create the struct and how its going to look like, and then you can start creating how many instances of it as you want :)
Related
I have struct
struct Course{
int cId;
string courseName;
};
and I want to add students for each Course. I thought to define another struct in to struct Course like
struct Course{
int cId;
string courseName;
struct Student{
int sId;
string studentName;
};
};
if I define struct like this how could I use it ? I have Course * cptr = new Course[1];
which for using the struct course.
How could I add Students to specified cId's ?
Your Course does not contain a Student. It just defines a struct of that name, i.e. a type Course::Student. For a type to contain an instance of another type, you just have to declare a member variable:
struct Student { .... };
struct Course
{
....
Student student;
};
If you want each course to hold more than one Student, then you can use a container. In the absence of more information, the best candidate for that is std::vector:
struct Course
{
....
std::vector<Student> students;
};
struct Course
{
// ...
struct Student
{
int sId;
string studentName;
};
};
This defines a struct Course and another struct Course::Student, but Course does not instantiate any student (there is no member of Course which has a type Student). If you want students to be a member of course, you need something like this:
struct Course
{
// ...
struct Student
{
int sId;
string studentName;
} student;
};
or
struct Course
{
// ...
struct Student
{
int sId;
string studentName;
} students[10];
};
Which would define a single student or an array of 10 students as members of Course, respectively. (NOTE: std::vector would be a better choice than a statically sized array)
Alternatively, you can declare Student as a struct outside of Course:
struct Student { ... };
struct Course
{
// ...
Student student;
// or std::vector<Student> students;
// or std::array<Student, 10> students;
// or Student* students
};
A very simple way:
struct Student
{
int sId;
string studentName;
};
struct Course
{
int cId;
string courseName;
std::vector <Student> students;
};
This way you may write
Student s;
Course c;
c.students.push_back(s);
std::vector is your friend, but if you are not allowed to use that, you can do:
struct Student {...}; // Implementation omitted for brevity...
struct Course
{
Student *students_; // Use students_=new Student[num_students]; to allocate
// memory dynamically
};
I prefer you to divide this struct into two individual struct. Then you can initialize a student object in the Course struct. Or u can implement a function in Course struct to link with Student struct.
Hello I am trying to create a new structure inside my class but i think there is an issue with public and private scope of some sort.
typedef struct Currency
{
Currency(Coin *coin, Currency *next, int _position) : _coin(coin), _next(next), _position(0) {}
Currency() : _next(NULL), _position(0) {}
Coin *_coin;
Currency *_next;
int _position;
};
that is my structure that is inside my public section of my class
and when I try to do this
if(location <= exit)
{
start = location + 11;
begin = response.find("label", start);
end = begin - start - 3;
findStrings(start, end, s, &response);
curr._next = new Currency();
}
it says Expected type specifier for the new Currency() call.
is there something i am missing or should structures not be used this way?
class Exchange
{
public:
typedef struct Badge
{
Badge(std::string id, Badge next, Badge prev, int length) : _id(id), _next(&next), _prev(&prev), _position(length) {}
Badge() : _id(""), _next(NULL), _prev(NULL), _position(0) {}
std::string _id;
Badge *_next;
Badge *_prev;
int _position;
};
typedef struct Currency
{
Currency(Coin *coin, Currency *next, int _position) : _coin(coin), _next(next), _position(0) {}
Currency() : _next(NULL), _position(0) {}
Coin *_coin;
Currency *_next;
int _position;
};
/* constructor and destructor */
Exchange();
Exchange(std::string str);
~Exchange();
/* Assignment operator */
Exchange& operator =(const Exchange& copyExchange);
void parseTradePairs(Currency curr, const std::string response, int begin, int exit);
private:
std::string _exch;
Currency *_currencies;
Badge *_ident;
};
endif
^ that is in the class header
Exchange::Exchange()
{
_exch = "";
}
Exchange::Exchange(std::string str)
{
_exch = str;
_ident = new Badge;
_currencies = new Currency;
std::string pair;
std::string response;
CURL *curl;
getTradePairs(curl, response);
int exit = response.find_last_of("marketid");
parseTradePairs(*_currencies, response, 0, exit);
}
void parseTradePairs(Exchange::Currency curr, std::string response, int begin, int exit)
{
int start;
int end;
string s;
int location = response.find("marketid", begin);
if(location <= exit)
{
start = location + 11;
begin = response.find("label", start);
end = begin - start - 3;
findStrings(start, end, s, &response);
curr._next = new Currency();
}
}
^that is in the class cpp obviously.
Your function definition in the .cpp isn't related to the Exchange class. You'll need to write:
void Exchange::parseTradePairs
(Exchange::Currency curr, std::string response, int begin, int exit)
{
// ...
}
Also: Anywhere outside your class scope you'll need to use Exchange::Currency to access the type.
If you're instantiating Currency within a method of the class, then this should work fine.
But if you're instantiating Currency elsewhere, you'll need to scope it with the class' name.
I.e. ClassName::Currency
Of course Currency needs to be visible in the scope that you do that, and making it public should take care of that.
(Note: This not an answer to edited question, downvote to request deletion... :-)
One issue is this:
typedef struct Currency {
};
It compiles, but C++ compiler should say something like warning: 'typedef' was ignored in this declaration (and if it does not, enable warning!). You should use one of these:
struct Currency {
}; // type 'struct Currency' With implicit typedef in C++
which in C++ is essentially same as:
typedef struct Currency {
} Currency; // explicit typedef
or
typedef struct {
} Currency; // anonumous struct With typedef type name
It is generally best to use the first form in C++. There may be subtle differences in some corner cases, so keep things simple.
C does not do the implicit typedef, so 2nd or 3rd form are sometimes used to avoid needing to use struct keyword everywhere. This is good to know because many libraries have same .h files for both C and C++.
I have a question about the following code in C++:
typedef struct {
int id;
int age;
} Group1;
typedef struct {
int id;
char name;
float time;
} Group2;
typedef union {
Group1 group1;
Group2 group2;
} ServiceData;
typedef struct {
ServiceData data;
} Time;
Then I have a variable:
Group1 * group1;
group1 = new Group1;
group1->id = 10;
group1->age = 20;
Then there are two methods defined like this:
void method1(ServiceData * data) {
//inside the method call method hello
hello(data);
};
void hello(Group1 *group1) {
printf("%d",group1->id);
}
I call method1 like this:
method1((ServiceData *)group1);
But inside method1, when the parameter group1 is passed to method hello(), I want to get the value of id inside of group1. Do I need to do any cast in hello method? Or inside of method1, do I need to cast it to (group*) before I pass it to hello()?
You don't need a cast, just to access the correct field in the union:
void method1(ServiceData * data) {
//inside the method call method hello
hello(&data->group1);
};
Instead of
method1((ServiceData *)group1);
you should do something like this:
ServiceData data;
data.group1.id = 10;
data.group1.age = 20;
method1(data);
And the implementation of method1 should look like
void method1(ServiceData * data) {
hello(&data->group1);
};
Of course, you must write
hello ( (Group1 * ) data);
(or write data->group1, other answer).
But do not do that, but use inheritance, if it's C++:
struct GroupBase {
int id;
virtual ~GroupBase {
}
}
struct Group1 : public GroupBase {
int age;
virtual ~Group1 { }
}
struct Group2 : public GroupBase {
char name;
float time;
virtual ~Group2 { }
}
void method1 (GroupBase* data) {
hello (std::dynamic_cast<Group1*> (data));
}
Is there a method I can use to be able to declare a new object w/ inherited variables with a single line of code? Example:
#include <iostream>
using namespace std;
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t : item_t
{
string material;
double size;
};
int main ()
{
hat_t fedora; // declaring individually works fine
fedora.name = "Fedora";
fedora.size = 7.5;
// this is also OK
item_t hammer = {"Hammer", "Used to hit things", 6.25};
// this is NOT OK - is there a way to make this work?
hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5};
return 0;
}
Classes with inheritance are not POD and therefore are definitely not aggregates. If you are not using virtual functions, prefer composition to inheritance.
struct item_t {
string name;
string desc;
double weight;
};
struct hat_t
{
item_t item;
string material;
double size;
};
int main ()
{
// this is also OK
item_t hammer = {"Hammer", "Used to hit things", 6.25};
// this is now valid
hat_t cowboy = {"Cowboy Hat", "10 gallon hat", 4.5, "straw", 6.5};
return 0;
}
I believe having base classes prevents the aggregate initialization syntax in C++03. C++0x has more general initialization using braces, and so it is more likely to work there.
Can you maybe just use a constructor?
struct item_t {
item_t(string nameInput, string descInput, double weightInput):
name(nameInput),
desc(descInput),
weight(weightInput)
{}
string name;
string desc;
double weight;
};
struct hat_t : item_t
{
hat_t(string materinInput,d double sizeInput string nameInput, string descInput, double weightInput) :
material(materialInput), size(size), item_t(nameInput, descInput, weightInput)
{}
string material;
double size;
};
then you can just call the constructor you want.
how allocate memory dynamically for the array of stucture....
eg:
class students
{
struct stud
{
int r_no;
char name[20];
}*s;
}
how to allocate memory dynamically for *s...
First of all, this is not the way of doing it, as you could use a vector of stud, for instance. With the code as you have it, it would be something like:
class students
{
public:
struct stud ... *s;
students() // ctor
{
s = new stud[100]; // say you have 100 students
// from now on you can use s[0], s[1], etc. in the class
}
};
However, what you should be using is kind of an STL vector or list:
class students
{
public:
struct stud ... ;
std::vector<stud> my_students;
students() // ctor
{
stud aStudent = {0, "Student Name"};
my_students.push_back(aStudent); // add a new student.
}
};
Why the extra wrapping of the struct in a class with nothing but a pointer?
Anyway, in C you'd do something like this:
struct stud
{
int r_no;
char name[20];
} *s;
size_t num_students = 4711;
s = malloc(num_students * sizeof *s);
Then it'd be prudent to go through and make sure all those individial structs are initialized, of course.
If you mean this to be C++, you should write constructors that take care of that, and use a new[] to allocate an array of structures.
You should make use of standard components when you can. Here std::string and std::vector would help you.
struct Student
{
int r_no;
std::string name;
};
typedef std::vector<Student> StudentList;
With such an approach, there is no point in wondering how to dynamically allocate memory. Everything's taken care of !
EDIT:
I simply typedef'ed StudentList because to me, adding more functionality to it would have been unrelated to the question.
Clearly, the last line can be replaced with a true class definition:
class StudentList
{
public:
// Add your own functionalities here
private:
std::vector<Student> m_students;
};
class students
{
public:
students(size_t noOfStudents):m_noOfStudents(noOfStudents)
{
s = new stud[m_noOfStudents];
}
~students()
{
delete s;
}
private:
struct stud
{
int r_no;
char name[20];
}*s;
size_t m_noOfStudents;
}