Maps and Arrays - c++

I'm working on a project for school and i'm trying to create a map that uses an array of size 2 as the index for the map. I'm not even sure if this is possible since I don't know I could access the elements of the map (since I really don't know how i could reference an entire array by value). Basically i'm trying to use the map index as a coordinant system to strings. If anyone could let me know if this is even possible and if it is what the syntax would be that would be a great help. Thanks!
I'm doing this prject in c++

If using Java, one approach you could use is to wrap your array with a class, and then implement the hashCode and equals method. These methods are a mechanism which allow other objects to identify an instance of that class. For example, the Map class uses hashCode as the key to store and retrieve that object.
Here's an example of your wrapper class.
class Point {
private int[] coordinates;
public Point(int x, int y){
this.coordinates = new int[]{x, y};
}
#Override
public boolean equals(Object o){
// implement equals as stated in the docs.
}
#Override
public int hashCode(){
// implement hashCode as stated in the docs using coordinates[0] and coordinates[1]
}
}
class App {
public static void main(String[] args){
Map<Point, String> map = new HashMap<Point, String>();
map.put(new Point(1,2), "some string");
// etc...
}
}

Well, the easiest way is to just concatenate the values into a string (assuming it's something simple) If you are using ints or floats just represent {1.2, 4.3} as a string "1.2,4.3" and make your map keys of type string.
ggreiner's answer is a good Java implementation and I've included a comment on his for the C# implementation, but I wouldn't be able to help you on generating a hash code in C++. However, if this is for homework, converting the array to a string will work and is probably what your instructor is expecting.

Related

C++ load constructor from variable name

I have a school project in which there is a world simulation. Teacher wants me to do save/load system and I've encountered a problem. My data is saved in a format name x y so saving works fine.
Problem starts when I want to load data. This is my solution:
switch(name) {
case "Human":
new Human(x,y);
break;
case "Dog":
new Dog(x,y);
break;
}
Is there a way to generalize this? Saved name is always exactly the same as constructor name, so I would just like to do something like:
string name = "Human"
new <name>(x,y) <-> new Human(x,y);
My solution works just fine but following the rules of OOP, the world shouldn't know what kind of organisms live on it.
No, currently there isn't. C++ doesn't have reflection and introspection which is required for something like this to work. (There is active work being done in this direction, but don't expect it to come into standard very soon).
There are serialization libraries which will hide the equivalent of your intended switch and provide a simpler, safer API and they are the preferred way to do this in production, but for your assignment you should do it manually.
By the way, your code is syntactically incorrect, it shouldn't compile, but I guess I get what you meant.
You can simplify the process of string comparison using macros. But you still have to provide a list of classes that need to be searched.
#define CHECK_RETURN(name, className) if (name == #className) return new className();
std::string name = "Dog";
CHECK_RETURN(name, Human);
CHECK_RETURN(name, Dog);
CHECK_RETURN(name, Banana);
No. Not in C++. To do that you would need reflection, and that is not a thing C or C++ can do.
What is done in some cases is to write an Interface Definition Language, aka IDL, and from that generate code that implements the interface. These interfaces often include the ability to serialize and deserialize objects in order to send them across the network, but it works for files as well.
That's probably more than you want to get into.
What you want for a simple C++ project is to implement a Factory. I assume all these things are Organisms so you want an OrganismFactory like:
class OrganismFactory {
public:
static std::unique_ptr<Organism> Create(const std::string& line);
};
And then it reads the contents of a line and produces an Organism. Probably using something like your case statements. Or you can create a std::map or std::unordered_map of the class name and a function pointer to the rest of the line. Then there's no if or case for each object type, just a map lookup and an indirect function call. You still have to write the code to fill in the map though, and write each function.
And yes by OOP rules you need to create interfaces/virtual methods in the Organism base class for everything that Organisms do in the world.
You can create your own lookup table of creator functions to handle this, for example:
class Organism
{
public:
virtual ~Organism() {}
};
class Human : public Organism
{
...
};
class Dog : public Organism
{
...
};
...
using OrganismPtr = std::unique_ptr<Organism>;
using CreateFunc = OrganismPtr(*)(int, int);
std::map<std::string, CreateFunc> mymap;
mymap["Human"] = [](int x, int y) -> OrganismPtr { return new Human(x, y); }
mymap["Dog"] = [](int x, int y) -> OrganismPtr { return new Dog(x, y); }
...
string name = "Human";
OrganismPtr o = mymap[name](x, y);
// use o as needed...

Access Key from Values and Value from Key

My project needs both accessors.
Access Value using Key (Simple)
Access Key using Value (Bit tricky)
Value too will be unique in my project
Please suggest the better container to use and how ?
I would like to use either the STL or BOOST.
What you're looking for is called a bidirectional map.
There isn't one in the STL, but you can take a look at Boost.Bimap for another implementation.
If you want to implement it yourself, you can simply use two regular one-way maps. If you use pointers, there should be little memory overhead and decent performance.
That's what I used in my project two days ago.
#include <boost/bimap.hpp>
class ClientManager
{
typedef boost::bimap<
boost::bimaps::set_of<int>,
boost::bimaps::set_of<int>
> ConnectedUsers; // User Id, Instance Id
ConnectedUsers m_connectedUsers;
public:
int getUserId(int instanceId);
int getInstanceId(int userId);
};
int ClientManager::getInstanceId(int userId)
{
auto it = m_connectedUsers.left.find(userId);
return it->second;
}
int ClientManager::getUserId(int instanceId)
{
auto it = m_connectedUsers.right.find(instanceId);
return it->second;
}
...
// Insert
m_connectedUsers.insert(ConnectedUsers::value_type(id, instanceId));
// Erase
m_connectedUsers.left.erase(userId);
If you want the either way access, ie key->value and value->key, chances are that your design doesn't need an associative container like a map
Try a vector of std::pair.
On a side note, if you need to store more than two values, you can use std::tuple.
HTH!!

Whats the most effective way to store a chemical formula?

I currently have have a HashSet of NElement objects. Each NElement object has a unique Element field, and an integer n.
Here are 2 operations I need to do with the data:
Iterate over all the values in collection.
With Element e, search the collection for an instance of NElement that has e and process it.
Here's an example of #2:
public void Add(NElement ne) {
foreach(NElement ne2 in elements) { //elements is the HashSet
if(ne2.element == ne.element) {
ne2.Number += ne.Number; //Number is the integer
return;
}
}
elements.Add(ne);
}
I think there is a better way to accomplish this using a collection other than a List or Set. Any suggestions?
A possible solution would be a bit of a different design. A molecular formula consists of a bunch of elements along with how many of those elements there are. So a possible solution is to have a MolecularFormula class that wraps this information, which is based in a
Map<Element, int>.
A possible example:
public class MolecularFormula
{
private Map<Element, int> elements = new HashMap<Element, int>();
//... Constructors etc
//A list to iterate through all values
public List<NElement> getElements()
{
List<NElement> retList = new ArrayList<NElement>();
foreach(Element e : elements)
{
retList.put(new NElement(e, elements.get(e));
}
return retList;
}
//To add something
public void add(Element e, int num)
{
if(elements.containsKey(e))
{
int newNum = elements.get(e) + num;
elements.remove(e);
elements.put(e, newNum);
}
else
{
elements.put(e, num);
}
}
}
This is hastily thrown together and not very efficient at all, but it should give you an idea of a possible option.
Try using SMARTS, SMILES, InChi or ASL. The first two are open source, I believe. InChi is maintained by the IUPAC, and is nicely hashable for database use. ASL is proprietary to Schrödinger, Inc, though if you are already using Schrödinger software, I'd recommend using their Python API directly.
Using any of these tools, you could find functional groups (or atoms) described by a specific SMARTS/SMILES/ASL string within a molecule described by SMARTS/SMILES/ASL.

how to create a comparator of key in a map where the value of the key is a string in java?

how to create a comparator of key in a map where the value of the key is a string in java?
because i want to swap values of the keys in the map?
is there a way to sort this numbers stored in a string variable?
TreeMap<String,List<QBFElement>> qbfElementMap = new TreeMap<String, List<QBFElement>>();
27525-1813,
27525-3989,
27525-4083,
27525-4670,
27525-4911,
27526-558,
27526-1303,
27526-3641,
27526-4102,
27527-683,
27527-2411,
27527-4342
this is the list of keys and the value for each of the key is a list.
now, how can i sort this key in ascending order by number.
ex. if i want to sort : 1,2,11,20,31,3,10
i want to have as output is : 1,2,3,10,11,20,31
but when i use the autosort of treemap the output goes : 1,10,11,2,20,3,31
how can i sort it in ascending order by numeric?
and the language is java :) thank you:)
When you create the TreeMap, provide a Comparator that sorts in the way you are expecting.
Map<String,List<QBFElement>> qbfElementMap =
new TreeMap<String,List<QBFElement>>(new Comparator<String>() {
#Override
public int compare(Object o1, Object o2) {
// compare your strings in ways that you understand
// presumably 11111-0000 sorts before 11111-0001
// left as an exercise for the reader
}
#Override
public boolean equals(Object o) {
return this == o;
}
});
But read the documentation for Comparator, including the bit about implementing Serializable, as it's particularly noted when using the Comparator in serializable data structures, like TreeMap
You may want to override the default comparator function for String with your own.
Since this could screw up the comparison of other Strings, I recommend defining a NumericString class that contains the String and implements Comparable and using that instead of String in your map.

Good practice for choosing an algorithm randomly with c++

Setting:
A pseudo-random pattern has to be generated. There are several ways / or algorithms availible to create different content. All algorithms will generate a list of chars (but could be anything else)... the important part is, that all of them return the same type of values, and need the same type of input arguments.
It has to be possible to call a method GetRandomPattern(), which will use a random one of the algorithms everytime it is called.
My first aproach was to put each algorithm in it's own function and select a random one of them each time GetRandompattern() is called. But I didn't come up with another way of choosing between them, than with a switch case statement which is unhandy, ugly and inflexible.
class PatternGenerator{
public:
list<char> GetRandomPattern();
private:
list<char>GeneratePatternA(foo bar);
list<char>GeneratePatternB(foo bar);
........
list<char>GeneratePatternX(foo bar);
}
What would be a good way to select a random GeneratePattern function every time the GetRandomPattern() method is called ?
Or should the whole class be designed differently ?
Thanks a lot
Create a single class for each algorithm, each one subclassing a generator class. Put instances of those objects into a list. Pick one randomly and use it!
More generically, if you start creating several alternative methods with the same signature, something's screaming "put us into sibling classes" at you :)
Update
Can't resist arguing a bit more for an object-oriented solution after the pointer-suggestion came
Imagine at some point you want to print which method created which random thing. With objects, it's easy, just add a "name" method or something. How do you want to achieve this if all you got is a pointer? (yea, create a dictionary from pointers to strings, hm...)
Imagine you find out that you got ten methods, five of which only differ by a parameter. So you write five functions "just to keep the code clean from OOP garbage"? Or won't you rather have a function which happens to be able to store some state with it (also known as an object?)
What I'm trying to say is that this is a textbook application for some OOP design. The above points are just trying to flesh that out a bit and argue that even if it works with pointers now, it's not the future-proof solution. And you shouldn't be afraid to produce code that talks to the reader (ie your future you, in four weeks or so) telling that person what it's doing
You can make an array of function pointers. This avoids having to create a whole bunch of different classes, although you still have to assign the function pointers to the elements of the array. Any way you do this, there are going to be a lot of repetitive-looking lines. In your example, it's in the GetRandomPattern method. In mine, it's in the PatternGenerator constructor.
#define FUNCTION_COUNT 24
typedef list<char>(*generatorFunc)(foo);
class PatternGenerator{
public:
PatternGenerator() {
functions[0] = &GeneratePatternA;
functions[1] = &GeneratePatternB;
...
functions[24] = &GeneratePatternX;
}
list<char> GetRandomPattern() {
foo bar = value;
int funcToUse = rand()%FUNCTION_COUNT;
functions[funcToUse](bar);
}
private:
generatorFunc functions[FUNCTION_COUNT];
}
One way to avoid switch-like coding is using Strategy design pattern. As example:
class IRandomPatternGenerator
{
public:
virtual list<int> makePattern(foo bar);
};
class ARandomPatternGenerator : public IRandomPatternGenerator
{
public:
virtual list<int> makePattern(foo bar)
{
...
}
};
class BRandomPatternGenerator : public IRandomPatternGenerator
{
public:
virtual list<int> makePattern(foo bar)
{
...
}
};
Then you can choose particular algorithm depending on runtime type of your RandomPatternGenerator instance. (As example creating list like nicolas78 suggested)
Thank you for all your great input.
I decided to go with function pointers, mainly because I didn't know them before and they seem to be very powerfull and it was a good chance to get to know them, but also because it saves me lot of lines of code.
If I'd be using Ruby / Java / C# I'd have decided for the suggested Strategy Design pattern ;-)
class PatternGenerator{
typedef list<char>(PatternGenerator::*createPatternFunctionPtr);
public:
PatternGenerator(){
Initialize();
}
GetRandomPattern(){
int randomMethod = (rand()%functionPointerVector.size());
createPatternFunctionPtr randomFunction = functionPointerVector.at( randomMethod );
list<char> pattern = (this->*randomFunction)();
return pattern;
}
private:
void Initialize(){
createPatternFunctionPtr methodA = &PatternGenerator::GeneratePatternA;
createPatternFunctionPtr methodB = &PatternGenerator::GeneratePatternB;
...
functionPointerVector.push_back( methodA );
functionPointerVector.push_back( methodB );
}
list<char>GeneratePatternA(){
...}
list<char>GeneratePatternB(){
...}
vector< createPattern > functionPointerVector;
The readability is not much worse as it would have been with the Design Pattern Solution, it's easy to add new algorithms, the pointer arithmetics are capsuled within a class, it prevents memory leaks and it's very fast and effective...