Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I want to store theses string vectors as a 4 dimensional vector. It has been three days that I am searching and I can not decide wether use multidimensional vector,boost multi array ,array of struct ,...
I am so new to cpp and they are so confusing.
vector < string >ID;
vector < string > firstName;
vector < string > lastName;
vector < string > address;
vector<vector<vector<vector<string> >>> person ;
what should I do for populating person ?
As suggested by #hansmaad
The following would be a simpler and better implementation(compared to mulch-dimensional vectors) for storing personal details in your program.
Define a person as:
struct person {
std::string id;
std::string first_name;
std::string last_name;
std::string address;
};
And define your vector as:
std::vector< person > people;
In your case, there is no point in creating multidimensional array. I'd rather try:
class Person
{
public:
string Id;
string firstName;
string lastName;
string address;
};
(...)
vector<Person> People;
// Adding
Person p;
p.Id = "1234";
People.push_back(p);
// Count
std::cout << "Currently you have " << People.size() << " people in the database";
// Access
Person p1 = People[0];
Edit: In response to comments
It's quite tough to answer the question without some specifics about your problem. From what little I know about it, I'd probably go into multi-class version:
class Id
{
public:
int Value;
std::vector<FirstName> Names;
}
class FirstName
{
public:
string Value;
std::vector<SecondName> SecondNames;
}
class SecondName
{
public:
string Value;
std::vector<Address> Addresses;
}
class Address
{
public:
string Value;
}
structure of arrays may be ! Or for a better readable and changeable code use a class
Related
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 2 years ago.
Improve this question
I get error when tring to access a private member of a class. My aim was to create a class, make an object and then access what was inputted into it.
So I created a User1.hpp file for my declarations.
class user1 {
private:
string username1;
string email;
string mobile;
public:
user1(string Myfirstname , string emailaddress , string mobile); //constructor
};
In my User1.cpp file, I implemented the class
user1::user1(string Myfirstname , string emailaddress , string mobile)
{
user1::username1 = Myfirstname;
user1::email = emailaddress;
}
then in main.cpp I created the first object and inputted some random data.
user1 firstman {"John" , "john1#email.com" , "011000000"};
Now when I want to see what 'firstman's email was in main.cpp, I tried this:
cout<<"Created "<< firstman.username1 <<" !"<<endl;
Which gives me the error of a private member. What is the best approach to accessing that data?
Private members are meant to be inaccessible from outside the class. You could make username1 public and const:
#include <iostream>
#include <string>
class user1 {
public:
const std::string username1;
user1(std::string Myfirstname, std::string emailaddress, std::string); //constructor
private:
std::string email;
std::string mobile;
};
user1::user1(std::string Myfirstname, std::string emailaddress, std::string): username1(Myfirstname), email(emailaddress) {}
int main() {
user1 firstman {"John" , "john1#email.com" , "011000000"};
std::cout << "Created " << firstman.username1 << " !\n";
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
For my assignment I have to make a program to read student data from standard input, sort it by last name / first name, and print out the result to standard output. Students consists of a last name, first name, and a grade point average. It says to there are no more than 50 students.
It also says you should not rely on an external library function to do the sort.
Here is the example:
Ware Henry 87.2
Dantes Edmond 91.4
Earhart Amelia 92.6
Here is how it should be sorted:
Dantes Edmond 91.4
Earhart Amelia 92.6
Ware Henry 87.2
Here is the code I have so far that is not working properly:
#include <iostream>
#include <string>
using namespace std;
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}
student::student()
{
Fname = "";
Lname = "";
gpa = 0;
}
void student::input()
{
cout << "Enter first name, last name, and gpa"<<endl;
cin >> Fname >> Lname >> gpa;
}
void student::sort()
{
char temp;
int count = 0;
int i = 1;
while (i < word.size()) {
if (word[i - 1] > word[i]) {
temp = word[i];
word[i] = word[i + 1];
word[i + 1] = temp;
i++;
if (i >= word.size())
{
alpha(word);
}
}
else
{
count++;
}
}
return word;
}
void main()
{
student.input();
}
Any advice on where I went wrong and any possible solutions?
your student class has member variables to hold only one student, you need 50 instances of class student.
then you should hold these instances in an array/vector (whatever for container you are allowed to use) I assume you need to use a raw array so something like this will do.
student* students = new student[50];
what you then need is a compare function in your class to be able to sort the array, the compare function knows the internals of your class and you can decide how you want to sort the list e.g. after surname.
the sort function could be inside your class declared as a static function or maybe more logically an external function since student is not a container of student instances.
don't forget to delete the array when done
delete [] students;
in real world problems you would use std containers and e.g. algorithm sort for this kind of work.
Your compiler must have told you that word and alpha used in sort method are undeclared identifiers and count is assigned but never used.
Solution: Never ever steal code from wild wild web without understanding what it does. You may take others' code as inspiration, but blind copy-paste is a big no-no.
To give you a next step: you haven't even stored your students, you just input one, how would you sort just one entry? Think (and code) what you should use to store them and start working from there on how to sort them.
Good luck.
There are several reasons why your code is not working, first reason is that your class definition needs semicolon ';' at the end to close it.
class student
{
public:
student();
void input();
void output();
void sort();
private:
string Fname;
string Lname;
float gpa;
}; //semicolon here
In your sort() method the variable word is used but never declared, coding is not magic, the variable must declared and initialized before it is used like in your code.
while (i < word.size()) { //word must be declared somewhere
Also, in the sort method, you call a function alpha(word), this function does not exist in your program.
The sort method is of type void, which means it will not return anything, yet you are trying to return a string.
Another problem with the sort method is that it is never called from anywhere and will never be run.
There is also a big problem here with the way you are trying to use your class. To use the methods of the class you first have to instantiate an object of that class, you can then access the methods of the class through the object like this:
int main()
{
student theStudent;
theStudent;
theStudent.input();
return 0;
}
Another fundamental problem is that you are only going to get data for one object like this, you need to store several objects in something like an array and then sort the objects in the array:
int main()
{
student students[5];
for (int i = 0; i < 5; i++)
{
student newStudent;
students[i] = newStudent;
newStudent.input();
}
sort(students);
delete[] students;
return 0;
}
Which brings us to the sort method. It would be wise to not do the sorting as a method of the student class, but as a function called from main instead (like in the example above), that way it is easy to sort the array of student objects from main.
These are a few advice to start with, i am not going to do your complete homework for you though, if you use google and some of your precious energy, i believe that you will succeed.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I started learning C++ and now I am lost, I don't see the logic in this. simply does not make sense to me how it is possible that I can add arguments to an object and then those arguments are used by the program. Sure I can memorize this feature, but can someone please explain the logic behind this? Everything else in C++ makes sense, I guess this probably does too, only I don't see it.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
class Person{
private:
string name;
int age;
public:
Person(){
name = "undefined";
age = 0;
};
Person(string newname){
name = newname;
age = 0;
};
Person(string newname, int newage){
name = newname;
age = newage;
};
string toString(){
stringstream ss;
ss << "Name is: " << name << " Age is : " << age;
return ss.str();
};
};
int main()
{
Person person1;
Person person2("David"); // I don't get this ???
Person person3("Mia", 35); // // I don't get this ???
cout << person1.toString() << endl;
cout << person2.toString() << endl;
cout << person3.toString() << endl;
return 0;
};
You are actually calling the constructors when you say you're passing arguments to objects. Constructors with matching signatures are called.
When you write Person person1;, default constructor which is
Person(){
name = "undefined";
age = 0;
};
is called.
When you write Person person2("David");,
Person(string newname){
name = newname;
age = 0;
};
is called.
And finally, when you do Person person3("Mia", 35);,
Person(string newname, int newage){
name = newname;
age = newage;
};
is called.
This statement: Person person1; is calling this constructor:
Person();
This Person person2("David"); is calling this constructor:
Person(string newname);
And this Person person3("Mia", 35); is calling this constructor:
Person(string newname, int newage);
Since constructors are functions that initialize the object of class Person, they can receive arguments, like any function.
When you define a new C++ class, with its members as your choice, each one of these functions as a regular variable (or pointers, or instances of other classes, etc.) which is a concept you are already familiar with.
So when you instantiate a new instance of the class, the compiler knows exactly how much memory it should allocate, and what is the inner structure of it - how to divide that memory into smaller pieces corresponding to the class members.
And that is how, when you call a constructor, it knows how to "add the arguments" to your instance.
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 6 years ago.
Improve this question
I want to use vector to store all Record. The Record class contains student and their age. It supposes to get the command and then call the specific method. However, when I compile it, it said "t is not declared". However, I have already declared as table t. How can I access the private vector without changing the visibility.
class student{
public:
int id;
string name;
student();
student(int,string);
};
class Record{
public:
student student;
int age;
};
class table{
public:
void Insert(student x,int y);
void Print(table t)
private:
vector <Record> records;
};
void Insert(student x,int y){
Record r;
r.student=x;
r.grade=y;
t.records.push_back(r);
}
void Print(table t){
sort( t.record.begin() , t.record.end() );
vector<Record>::iterator itr;
for( itr = t.record.begin() ; itr != t.record.end() ; itr++ )
cout << (*itr).student.id << '\t' << (*itr).student.name << '\t' << (*itr).age << endl;
}
int main (){
student x;
table t;
string command,name;
int id,age;
while ( cin >> command ){
if (command=="Insert"){
cin >> id >> name>> grade;
student s(id,name);
t.InsertStudent(s,grade);
}else if (command == "Print"){
t.Print(t);
}else{return 0;
}
}
The error message is:
t was not declared in this scope in t.records.push_back(r);
I have capitalized the class name and the problem still exist.
There are a significant number of problems with this code. So we'll address the 3 mistakes most closely related to your question: How can I access the private vector without changing the visibility?
You are calling: t.InsertStudent(s,grade). Since you declare table t, that will try to call class table's InsertStudent method. Which there isn't one. You probably intended to call the Insert method.
You define the function void Insert(student x,int y) which was likely intended as the method void table::Insert(student, int y). Note the class scoping on the definition. Alternatively, you could remove the declaration, and just use the definition directly in class scope.
You are trying to call t.records.push_back(r) where t is not a global object that this function would have access to. But presuming from 2 that you intended to define this as a method you would not use an object name to access member variables, instead you could directly access the member variables: records.push_back(r)
I've tried to briefly explain how to fix stuff, but there are some underlying conceptual problems here that need to be addressed, which probably can't be addressed in a couple sentences. Please at least read through: http://www.cplusplus.com/doc/tutorial/classes/ before asking follow up questions. If any of my answer remains unclear after reading through that, feel free to comment below.
As far as other errors in the code start by looking over the line that the compiler issues the waning on. If you can't solve it using that feel free to open a new question posting the code and error.
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 7 years ago.
Improve this question
I had the below C++ question in the recent interview but could not do. Please help.
Given a company structure where every employee reports to a superior, all the way up to the CEO, how would you print out all the employees that a particular individual oversees?
Write a method that implements this, given the below:
// Employee object contains a string denoting the.
// employee name, and an array containing
// employees who report to this employee
Employee {
String name;
Employee[] employees;
}
I have seen and understand the recursive function. But I have not encounter such a recursive object/structure like this one.
My new question is how can an object is created and initialized from this class/structure since it is recursive?
Thank you very much again.
With the information given it is very hard to answer (and question should probably be set on hold). Anyway...
I think a recursive approach is the answer. You need a function that can take a name, search the full employee list for that name and then call the function again for every employee in the local array. Something like:
void doit(Employee& e)
{
// Print e.name
// For each employee tmp in e.employees (i.e. local array)
doit(tmp);
}
Note - this requires that there are no loops in manager-employee arrays. If there is this will be an endless loop. So this is a dangerous approach.
EDIT:
This is added due to the comment from OP.
As indicated above the question is vague and doesn't really give sufficient information to provide a good answer. The struct given in the question is not valid C++ and there is no description of how the company wide list of employees are maintained.
However to keep it simple, the printing could look like this:
struct Employee
{
void PrintAllReportingEmployee(int level)
{
cout << string(4*level, ' ') << name << endl;
level++;
for (auto& e : employeesDirectlyReportingToThisEmployee)
{
e.PrintAllReportingEmployee(level);
}
}
string name;
vector<Employee> employeesDirectlyReportingToThisEmployee;
};
// Code in some print function:
// Step 1 - find the relevant employee
Employee tmp = SomeFunctionReturningAnEmployeeBasedOnName("NameOfPerson");
// Step 2 - print all employees reporting directly and indirectly
tmp.PrintAllReportingEmployee(0);
This assumes a single top-level Employee (e.g. director) with a vector of employees directly reporting to the director. Each of these would then have a vector of employees reporting to them and so. So it is kind of an tree structure.
Note, if I should design a employee db, I would not go with such a solution.
Who ever asked the question was looking for an answer with something to do with class inheritance. So a class Persion is extended by Employee where Person is also extended by Manager etc etc where they all share some similar properties but not everything.
This means that your code can be expanded upon by other programmers and one change can fix many different classes!
Although this code does not demonstrate class inheritance, it will work.
/*
THE OUTPUT:
Jacobs-MacBook-Pro:~ jacob$ ./employee
Foo McGoo
Bar Too
Jacobs-MacBook-Pro:~ jacob$
*/
#include <iostream>
#include <string>
#include <vector>
using std::string;
using std::vector;
using std::cout;
using std::endl;
/* define class (this should be in a header file) */
class Employee{
public:
//Variables
string Name;
//Functions
Employee(const string&); //constructor
void AddCoWorker(const Employee&);
void ShowCoWorkers();
private:
vector<Employee> employees;
}; //Note the semicolon
//Entry point
int main(int argc, char **argv){
Employee foo("Foo McGoo");
Employee bar("Bar Too");
Employee me("Bevis");
me.AddCoWorker(foo);
me.AddCoWorker(bar);
me.ShowCoWorkers();
return 0;
}
//Class functions (should be in a separate cpp file)
Employee::Employee(const string& name){
this->Name = name;
}
void Employee::AddCoWorker(const Employee &e){
this->employees.push_back(e);
}
void Employee::ShowCoWorkers(){
int count = this->employees.size();
for(int i = 0; i < count; i++){
//Print the names of each co worker on separate lines
cout << this->employees[i].Name << endl;
}
}