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 want to retrieve each element from the list of object in cpp and we have classes like below:
class User{
public:
bool isAvailable;
string value;
};
class Users{
public:
User dateFrom;
User dateTo;
User add1;
User add2;
};
Now somewhere else I have created a list of objects of User like std:: list<User> user-list, stored data and then pushback to the list of the object now I want to get that particular data like dateFrom,dateTo, etc.
user-list.push_back(dateFrom);
user-list.push_back(dateTo);
Now I want to access the element of user-list like what we access in list l1 by index like.
This is just a guess of what you might want:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class User {
public:
bool isAvailable;
string value;
};
int main()
{
User someuser;
someuser.value = "Some user";
someuser.isAvailable = true;
User someotheruser;
someotheruser.value = "Some other user";
someotheruser.isAvailable = true;
std::vector<User> user_list; // <<<< using std::vector here
user_list.push_back(someotheruser);
user_list.push_back(someuser);
cout << user_list[0].value << "\n";
cout << user_list[1].value << "\n";
}
We use a std::vector here instead of a std::list because you mention you wanted to access the elements of the list via an index.
Output is:
Some other user
Some user
Disclaimer: This code is still very poor, for example there are no constructors whatsoever.
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 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 3 years ago.
Improve this question
I have a large global map in a header of weapon names and ID numbers from a video game . I am trying to find a way that I can take user input for the name and return the item number. For this I created a new int and would like to initialize it with the map value after searching for the name. What is the best way to do this?
//header
#include <map>
#include <string>
using namespace std;
typedef std:: map <std :: string, int> weaponMap;
inline
weaponMap & globalMap() {
static weaponMap theMap;
static bool firstTime = true;
if (firstTime) {
firstTime = false;
theMap["weaponOne"] = 854000;
}
}
//Source.cpp
#includes "globalMap"
int swapWeapon = weaponMap::["weaponOne"];
cout << swapWeapon;
Well, there are multiple misconceptions you seem to have in your code:
//header
#include <map>
#include <string>
using namespace std;
typedef std:: map <std :: string, int> weaponMap;
inline
weaponMap & globalMap() {
static weaponMap theMap;
static bool firstTime = true;
if (firstTime) {
firstTime = false;
theMap["weaponOne"] = 854000;
}
return theMap; // this is necessary if you specify a return type
}
//Source.cpp
// #includes "globalMap" You have a typo here, that should be as follows
#include "globalMap"
// You cannot access the local static variable from the function in your code directly
// int swapWeapon = weaponMap::["weaponOne"];
int swapWeapon = globalMap()["weaponOne"]; // Note that this would initialize
// swapWeapon with 0 if "weaponOne"
// wasn't registered as a key
// You cannot use these statements outside of a function scope
// cout << swapWeapon;
int main() {
cout << swapWeapon;
}
See a live demo.
For this I created a new int and would like to initialize it with the map value after searching for the name.
In that case you need to move the initialization out from the global context:
int main() {
std::string weaponType;
std::cout "Input a weapon type: "
std::cin >> weaponType;
int swapWeapon = globalMap()[weaponType];
std::cout << swapWeapon;
}
More points
Do not use using namespace std; in header files (see here why)
In general avoid to have such flat Singleton Patterns, rather use a Abstract Factory to make your code more flexible for future maintenance.
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;
}
}
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
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming = {{1,"ONE"},{2,"TWO"}};
cout<<naming.numline<<":"<<naming.numname<<std::endl;
return 0;
}
This error occurs:
main.cpp:10:33: error: braces around scalar initializer for type int
} naming = {{1,"ONE"},{2,"TWO"}};
You have
struct naming { … } naming = …
which means you're creating a single naming object. But your initializer
{{1,"ONE"},{2,"TWO"}}
doesn't match that intent.
Looks like you're trying to initialize a collection of naming objects. If that's the case you should make it a std::vector<naming> instead of a single object:
struct naming { … }; // definition of naming
std::vector<naming> namings = {{1, "ONE"}, {2, "TWO"}}; // collection of objects
Then you can access the individual naming objects like so:
// access the first element:
std::cout << namings.at(0).numline << ":" << namings.at(0).numname << std::endl;
// access the second element:
std::cout << namings.at(1).numline << ":" << namings.at(1).numname << std::endl;
Since you want to store two values , you will have to create an array of structure type.
#include <iostream>
using namespace std;
int main()
{
struct naming
{
int numline;
string numname;
} naming[] = {{1,"ONE"},{2,"TWO"}};
cout<<naming[0].numline<<":"<<naming[0].numname<<std::endl;
cout<<naming[1].numline<<":"<<naming[1].numname<<std::endl;
return 0;
}
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
Is there some way I can have a global variable (in this case a vector) retain its contents throughout any functions? I'm trying to see if I can do this:
vector<string> collected_input; //global
void some_function{
string bla = "towel";
collected_input.push_back(bla); //collected_input gains "towel"
}
void some_otherfunction{
string xyz = "zyx"
collected_input.push_back(xyz); //collected_input gains "zyx"
}
int main(){
// print the contents of the collected_input vector
}
What you have shown will work just fine, provided main() is calling some_function() and some_otherfunction():
#include <ostream>
#include <vector>
#include <string>
using namespace std;
vector<string> collected_input;
void some_function()
{
string bla = "towel";
collected_input.push_back(bla);
}
void some_otherfunction()
{
string xyz = "zyx"
collected_input.push_back(xyz);
}
int main()
{
some_function();
some_otherfunction();
for (vector<string>::iterator iter = collected_input.begin();
iter != collected_input.end();
++iter)
{
cout << *iter << '\n';
}
return 0;
}
The code you posted will achieve what you are looking for. Your have a single instance of a vector (collected_input), which is used across multiple functions. Your vector is effectively global, and in fact it is possible for other source files to access it by declaring a vector of the same name using the extern keyword, although this is highly recommended against.
Of course, right now your program does nothing because your main() function does not contain any code. If you were to call both of your functions from main() and then print the vector, you will find that both functions successfully operated on the vector.