Getting enum Values by its index [duplicate] - c++

This question already has answers here:
Is there a simple way to convert C++ enum to string?
(35 answers)
How to convert an enum type variable to a string?
(35 answers)
Closed 8 years ago.
How can I access each value of the enum by the index?
for instance,
enum food{PIZZA, BURGER, HOTDOG};
as we all know, the index of the first element starts from 0 unless initialized.
How can I get the string value of the enum from the index?
How can I get it to print the PIZZA?
cout << food(0);
I know it's not correct, but please advise me thanks.

You can't get the string representation of an enum in c++.
You have to store them somewhere else.
Example
enum food{PIZZA, BURGER, HOTDOG}
char* FoodToString(food foodid)
{
char* foodStrings[3] = {"PIZZA","BURGER","HOTDOG"};
return foodstrings[foodid];
}

There's no way of doing that because there's no need to do that. Generally enums are used to replace integral values we use for example:-
int func ()
{
//...
if (something )
return 0;
return 1;
}
could be replaced with
enum Status { SUCCESS, FAILURE };
Status func ()
{
//...
if (something )
return SUCCESS;
return FAILURE;
}
for better readability.
If you want to get enum value by providing index then you can store index with enum values in some sort of map ( for unordered_map ).

Related

Is there any way to automatically declare a variable with the same type as the function's return type? [duplicate]

This question already has answers here:
When should I use C++14 automatic return type deduction?
(7 answers)
How to return arbitrary type in C++11 using auto keyword?
(6 answers)
Closed 8 months ago.
I don't want to declare the return value two times, so maybe there is a more clever way in modern C++ to do this, but I couldn't find any way.
So, instead of this:
int calculate() {
int ret=0;
return ret;
}
I want to do something like this:
int calculate() {
decltype(return_type) ret=0;
return ret;
}
It would make it easier to change the return type if needed.
If it's not possible, then why is it not possible?

When I run this code, result is always 24 regardless of what string is. Why? [duplicate]

This question already has answers here:
c++ sizeof( string )
(9 answers)
Closed 1 year ago.
When I run this code, result is always 24 regardless of what string is. Why?
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s = "asdccccc";
cout << sizeof(s);
return 0;
}
A string is an object. By using sizeof you are getting the size of the members of that object. One of those members is probably a pointer to the actual string contents, but the size of a pointer is constant no matter what it points to.
Consider this simple example
class string
{
const char* _ptr;
....
....
public:
}
When you write sizeof(string), you will get the size of the class, not the size of string literal _ptr points to.

return structure vs pass Reference variables [duplicate]

This question already has answers here:
Is it better style to initialize a structure by passing a reference or returning it?
(4 answers)
Closed 6 years ago.
Which one is better if I have to return a string as well as an array from a function.
Create a structure containing string and array, populate that and return the instance of that structure.
Consider I have to send string "status" and an array "ids".
struct ReturnValues {
string status;
int ids[10];
};
use it as:
ReturnValues returnValues;
returnValues = func();
Consider that func() returns the object of ReturnValues
Pass one of them as referenced variable and return the other.
As:
int ids[10];
string status = func(ids);
Consider that func takes ids as referenced variable
string func(int& ids) {
//Some code
return status;
}
Pass both as referenced variables returning void.
As:
int ids[10];
string status;
func(ids, status);
Consider that func takes ids and status as referenced variables
void func(int& ids, string& status) {
//some code;
}
Strictly from a performance standpoint, it would give the compiler the most leverage to optimize if you do :
struct ReturnValues {
string status;
int ids[10];
};
and
ReturnValues returnValues = func();
Doing
ReturnValues returnValues;
returnValues = func();
will decrease performance since return-value optimization cannot take place : http://goo.gl/5Cfmw2
I would definitely go for the 1st version. Functions that modify their arguments tend to make the code more difficult to understand and test.
If you are worried about performance: Practically all compilers will use return value optimization here. So this should not be an issue, maybe except in some exotic cases.
Personally I would either group them together either into a predefined struct as you did or use std::pair or tuple if you don't want to define one explicitly. My feeling is that things that belong together belong together (if you'll forgive the tautology). Either way I would consider using std::array if the array length is fixed or std::vector (or some collection type) if not. Am not a fan of level C type arrays such astype A[10] I would probably just return them as a return value simply because it shows the intent "Get me one of these things with ints and strings in it" and let the compiler sort it out

Using a user variable to access a member of struct? C++ [duplicate]

This question already has answers here:
How to use a string as a variable name in C++? [duplicate]
(2 answers)
Closed 7 years ago.
Say I have the following struct:
struct movie {
char movie_name[32];
int rating;
int release_year;
char location;
}
Normally, I would access the rating by saying "movie.rating".
For this project, I have to take input from a text file. I will read a variable such as "movie_name" or "rating" or "release_year" from the file, and given that variable, I have to access the corresponding element of the struct.
Ex: if the input file reads "movie_name", then I want to access movie.movie_name. How do I do this without making 4 if statements? Is there another way?
if(input == "movie_name")
movie.movie_name = ...
else if(input == "rating")
movie.rating = ...
The real struct I'm working with has 20+ members, so I am trying to find a more efficient way to write this code.
Thanks in advance!
In C/C++ it is not possible to access variable using a string; so there is no way to do this using the struct you provide. A map might be an alternative:
map<string, int>
but then each variable will map on the same type of variable (int in this case)... You should look to the related questions: How to use a string as a variable name in C++? and Convert string to variable name or variable type
What you are looking for is called reflection. unfortunately, it is not supported in C++. One solution to your problem which is not an optimal one of course is to implement your struct as map of pair<key,value> as follow:
struct movie {
std::map<string,ValueType> foo;
}
However, the problem is the ValueType. If boost is available, Then this could be a better solution:
struct movie {
std::map<string,boost::variant<typeX, typeY>> foo;
}

Number of "constants" in enum [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
(How) can I count the items in an enum?
Is there a way to get the number of constants in enum?
For example:
enum C{id,value};
And later this would return 2:
//pseudo code
get<C>::value
And also, is it possible to access those constants via [] optor? Like i.e.:
C[0] would return id
Usually, you start at zero and the last member gives the size of the enum excluding it.
enum C { id = 0, value, size };
C::size is the size of the enum. Is it possible to access those constants via subscript? No, it is unfortunately most assuredly not possible. However, in this case, you don't really want an enum- you just want a constant array.
A common idiom used for this is
enum C {
id,
value,
LAST_ENUM_C // or something similar.
};
but that assumes no gaps in the enum values here (i.e. no id = 3, value = 15).