Initialializing a struct with predefined values [closed] - c++

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;
}

Related

Retrieve element from list of Object in cpp [closed]

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.

C++ direct and copying initialization problem with constructor [closed]

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 have started doing C++ clases for over 2 weeks now and I have a small problem that i dont know how to solve. I have to make a simple Class with one int parameter. That class needs to work with direct and copying initilaization and needs to print message which initialization is used. For example:
TestClass T(60) //this should print a message "Direct initialization"
TestClass T = 205 // this should print a messagte "Copying initialization"
If you use a constructor with a single variable initialization, then this assignment operation will be done for you automatically. See my code below:
#include<bits/stdc++.h>
using namespace std;
class A {
int x;
public:
A(int xx) {
cout << "Constructor Called" << endl;
x = xx;
}
print() {
cout << "Value of obj is " << x << endl;
}
};
int main() {
A v = 10;
v.print();
}
Because you used initialization constructor, = operator was handled automatically. To prove that it is using the constructor, I used cout in constructor and created and called another printing function.

How to initialize an Int from a map Value, C++ [closed]

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.

C++: How can I used global variables in various different functions? [closed]

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.

Use a struct from a object? [closed]

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
I started with working code (not written by me obviously), I saw them make a class object dataflash which made sense to me, but then after that they used:
DataFlash::ID id;
Which is obviously because they needed an object of that struct, but the fact they went back to the DataFlash class bugged me, not sure why, but I thought "No, no, you should be using the object we just made now" and promptly changed it to what I have below, which produces the following error:
error: invalid use of ‘struct main()::DataFlash::ID’
Well that's no fair, I'm basically doing the same thing to my eye, why is this invalid use? Are structs (and nested classes I assume too) useless once they are in an object?
#include <iostream>
using namespace std;
int main()
{
class DataFlash
{
public:
struct ID
{
uint8_t manufacturer; /**< Manufacturer id **/
uint8_t device[2]; /**< Device id **/
uint8_t extendedInfoLength; /**< Extended device information**/
};
};
DataFlash dataflash;
dataflash.ID id;
return 0;
}
The code defines several layers of nested scope, the original code is doing scope resolution with the scope resolution operator ::
Your example uses a member access operator . and the struct ID simply is not a member, it lives in the scope of your type, a type and value is not the same thing.
As a footnote, enumerations can be accessed in both ways due to enum's scoping rules.
#include <iostream>
struct object {
enum identifier {
a = 2,
b = 16,
};
identifier id;
};
int main(int argc, char* argv[]) {
object obj;
std::cout << object::a << std::endl;
std::cout << obj.b << std::endl;
}