How to use variable to help pick member of struct to utilize - c++

In the program I am writing I have various structs with several members. Saved in several string I have different members of the structs names. How do I use those strings to choose the data from the member I want?
Example:
struct teams
{ double x;
double y;
};
teams cardinals = {1, 2};
teams pirates = {};
teams cubs = {};
team1 = "cardinals";
I want to do the equivalent of outputting team1.x but I have no idea how. Help?

C++ is a strongly typed language, so you really can't achieve this. There are languages like ruby which give you the feature of converting a symbol to a string and vice-versa.
As I understand your questions, What you probably are asking is to associate names for selecting structures. Based on this understanding, you could create enum, declare vector or array of structs and then use them
enum {CARDINALS=0, PIRATES, CUBS, MAX_SIZE};
struct teams
{ double x;
double y;
};
struct teams allTeams[MAX_SIZE+1];
teams[CARDINALS] = {1,2};
Hope it helps!

Related

Keys to access vector fields - enum class or enum in namespace?

Let's say I have an alias for vector:
typedef std::vector<double> PlanetData;
And I want it's fields to be accessible via some keys:
double x = planet_data[PlanetDataKeys::PosX]; //planet_data is of type PlanetData
How can I achieve it?
I can define an enum inside a namespace:
namespace PlanetDataKeys {
enum {
PosX = 0,
PosY = 1
};
}
But enum class is safer:
enum class PlanetDataKeys {
PosX = 0,
PosY = 1
};
However, as implicit casting of enum class to int type is disabled, this would require to write:
double x = planet_data[static_cast<int>(PlanetDataKeys::PosX)];
which is a bit awkward .
Which approach is better in this case and why?
EDIT Some explanation for aliasing vector:
In real code, PlanetData have ~7 fields, maybe even more if I decide to expand it. And I'm creating an instance of it while parsing a string of form data_string = "date: 2903248.12343, position=[124543254.1343214,123213.12341,63456.1234], velocity=[...". That's why I wanted it to be a vector: to use something like planet_data.push_back(ParseNextDouble(data_string));
Please don't expect too much functionality from a humble vector.
Vector is not designed to access it's data with keys other than indices. Despite your examples are syntactically and semantically correct, they look like a misuse of std::vector and enum classes. Each tool has it's purpose, and vector seems to be not the best one for your task.
Enum classes were introduced to improve type safety. With them, you'll never mix up PlanetDataKeys, SatelliteEphemeris and KeplerianOrbitElements. But in your case you finally cast any of them to int, loosing all the conquest of type-safe enums.
As to me, it would be better to define a PlanetData class with a subscript operator which accepts PlanetDataKeys as it's argument.
If you want to stick with vectors, I'd choose the first variant (with namespaces). It's much easier to read and write, and I'm convinced that it's not even a little safer than enum classes used this way.
What about just defining scoped constants of the appropriate type, like so:
namespace PlanetDataKeys {
const size_t PosX = 0;
const size_t PosY = 1;
}

Dynamic Structs in C++

For a project in C++ (I'm relatively new to this language) I want to create a structure which stores a given word and a count for multiple classes. E.g.:
struct Word
{
string word;
int usaCount = 0;
int canadaCount = 0;
int germanyCount = 0;
int ukCount = 0;
}
In this example I used 4 classes of countries. In fact there are hundreds of country classes.
My questions regarding this are the following:
Is there any way to generate this list of countries dynamically? (E.g. there is a file of countries which is read and on that basis this struct is generated)
Fitting for this struct should be a function which increments the count if the class is seen. Is there also a way to make this "dynamic" by which I mean that I want to avoid one function per class (e.G.: incUsa(), incCanada(), incGermany() etc.)
Since I'm not really used to C++: Is this even the ideomatic approach to it? Perhaps there's a better data structructure or an alternative (and more fitting) way to result the problem.
Thanks in advance.
In C++ class and struct definitions are statically created at compile time, so you can't, for example, add a new member to a struct at runtime.
For a dynamic data structure, you can use an associative container like std::map:
std::map<std::string, int> count_map;
count_map["usa"] = 1;
count_map["uk"] = 2;
etc...
You can include count_map as a member in the definition of your struct Word:
struct Word
{
std::string word;
std::map<std::string, int> count_map;
};
Consider std::map. You could create a map of countries to a map of words to counts. Or a map words to a map of countries to counts. Whether you use an enum or strings for your country codes is up to you.

Technical term to name the properties of a class that can take two values (true and false)?

Does a technical english word exist to commonly name the group of boolean members of a class that characterize it ?
EDIT : I'm not searching for the word "boolean". In the following example does a word exist to name the group of variable that begins by "is" ?
class MyClass
{
protected:
double x;
double y;
double z;
bool isBig;
bool isBeautiful;
bool isRich;
bool isBlackAndWhite;
};
EDIT : Flags is definitely the word I searched for.
'Traits' is one word to describe it, in general terms, but this already has a very specific meaning within C++ and what you're describing is not it.
My suggestion? Go to an online thesaurus, type 'traits' and take your pick of what comes back.
"Boolean" is the correct technical term for this structure and is born out of mathematics.
"Boolean" is the technical term for a variable which can be either true or false.
class Is { bool value; public: const bool get(void) { return value; } const };
I don't usually name "substructures" with a fixed dictionary of technical terms; I'm trying to use a name that tells what kind of data the structure contains.
Technically, booleans could also be called "flags", but I'm not positive that simply collecting all bools into a "flags" structure is really the way to go. structures should really only be used to form groups of items that actually belong together; if, for example, you find that you are naming some of your variables "Timer_xxx", then those variables might be a good candidate to go into a structure, which you would probably call "Timer".
In a similar fashion, you probably wouldn't do something like
struct { double x, y, z; } BigFloatyNumbers;
Instead, you would probably write it as
struct { double x, y, z; } Position;
Thus, in your case, maybe "Properties" is a reasonable name. It's even generic :-)

Extending an enum?

Say I create an enum but eventually someone wants to add items to that enum, what does one do?
ex:
// blah.hpp
enum PizzaDressing {
DRESSING_OLIVES = 0,
DRESSING_CHEESE = 1
};
and in my FunkyPizza class, there might be pepper toppings.
So how could I add peppers without obviously modifying the original enum?
Thanks.
This is closest to what you want: Base enum class inheritance
Since enums are typically handled as some size of int in the compiler, all you have to do is later make
enum PizzaDressing
{
Olives = 0,
Cheese = 1,
Pepperoni = 2
};
or you could allow it to count
enum PizzaDressing
{
Olives = 0,
Cheese = 1,
Pepperoni
};
You could, if neither of those is acceptable for some reason, use math (Cheese + 1).
You can play around with the enum in almost any way you could with a numeric value.
Note that the enumerator you use is typically baked into the code by the compiler, it doesn't show up as its name, simply value. Thus, modifying (extending) the enumerator later on will not effect code that has been built.
I think it's legal syntax to use an enumeration in another enumerator, with casts, but I've never tried it. This may work, but is kind of ugly:
enum PizzaDressing
{
Olives = 0,
Cheese = 1
};
enum OtherPizzaDressings
{
Start = (OtherPizzaDressings)PizzaDressing::Cheese;
Pepperoni
};
That would be known as a "dynamic enum". To the best of my knowledge, nothing like this exists in C++. However, since we're using C++ and not C, you could do something like this:
#include <string>
#include <map>
std::map<std::string, int> myMap;
myMap["DRESSING_OLIVES"] = 0;
myMap["DRESSING_CHEESE"] = 1;
myMap["PEPPER_TOPPING"] = 2;
You can't dynamically modify an enum, because it only defines a new type resolved at compile time. They are mnemonics for the programmer, at compilation they are translated to numbers.
That said, you can use any number not used by the original enum to represent whatever you want:
PizzaDressing a;
a = (PizzaDressing)5;

Questions on Scala from a C++ programmer (structs and stl)

I am having problems translating C++ data structures to Scala. Scala is really different from C++, but I like a lot of it.
I have the following Code fragment in C++:
struct Output
{
double point;
double solution[6];
};
struct Coeff
{
double rcont1[6];
double rcont2[6];
double rcont3[6];
double rcont4[6];
double rcont5[6];
double rcont6[6];
};
std::list<Output> output;
std::list<Coeff> coeff;
I now fill the list in a while loop with data
while(n<nmax) {
if step successfull
Output out;
out.point = some values;
out.solution[0] = some value;
output.push_back(out);
}
I tried creating a simple class in Scala to hold the data.
class Output
{
var point: Double
var solution: Array[Double] = new Array(6)
}
But this doens't work since point is not initialized. Is there a way around this? I just want to define the variable but not initialize it.
Another quick thing. I am looking for an equivalent to stl::lower_bound.
Is finds the right position to insert an element in an sorted container to maintain the order.
Thanks for helping a Scala beginner
Why don't you want to initialize it? For efficiency? I'm afraid that the JVM doesn't let you get away with having random junk in your variables based on whatever was there originally. So since you have to initialize it anyway, why not specify what your "uninitialized" value is?
class Output {
var point = 0.0
var solution = new Array[Double](6)
}
(You could use Double.NaN and check for point.isNaN if you later need to see whether the value has been initialized or not.)
You could use _ as the default initialization, but unless you use it in generic code:
class Holder[T] {
var held: T = _
}
then you're just obscuring what the value really will be set to. (Or you are announcing "I really don't care what goes here, it could be anything"--which could be useful.)
I just found the answer to the intialistion:
class Output
{
var point: Double = _
var solution: Array[Double] = Array(6)
}
Puh Scala has a lot of syntx to get used to :-)
Anyone have a solution for the lower_bound equivalent ?
It's hard to translate effectively, as you've left a lot of unknowns hidden behind pseudo code, but I'd advocate something along these lines:
// type alias
type Coeff = Seq[Seq[Double]]
// parameters passed to a case class become member fields
case class Output (point: Double, solution: Seq[Double])
val outputs = (0 to nmax) map { n =>
Output(generatePoint(n), generateSolution(n))
}
If you can flesh out your sample code a bit more fully, I'll be able to give a better translation.