Passing variable amount of objects as reference to a class - c++

I have library that im using to load images. The library makes class objects out of the files and has their own drawing functions. Im trying to build a class that can handle these objects and implement some simple logic once im done loading my files. What would be a good way to pass them as reference or pointer to my handling class?
This is what i got so far:
1) Passing them as reference one by one. When i add a file i will always have to write the new file to my class definition.
2) Loading all the objects into array and pass that as reference. I still have to set the class defition so that i know how many items are in the array. But what if i have different amount files to load at various steps of my program? Writing many constructor/function overloads doesnt seem like a right way to do it.
I searched for the weekend and didnt really find any solutions to this so any points and tips would be welcome. Oh and im pretty new to C++ so consider my knowledge limited. I can grasp the idea what the pointers and references are but implementing things with them are slow.
So to repeat my question. What would be a good way to pass variable amount of objects as reference or pointer to my handling class?

you can make your function look like this:
void my_function(std::vector<SomeObject *> &objs) {
// ...
}
and you can then iterate over the objs vector using an Iterator, or just check
objs.size()
see http://en.cppreference.com/w/cpp/container/vector

You did not include source code details about your issue but your solution # 2 should be fine and you can just pass an int variable to hold the number of elements in the array.

Related

How to assign dispatch_queue_t to variable in a structure

I'm still relatively new to Objective C and easily confused by the various types. I am using code from the SquareCam sample project, incorporated into a larger project. It works fine, but now I want to save the videoDataOutputQueue, which is of type dispatch_queue_t so that I can use it elsewhere in the project. It has to pass through some C++ code before finally ending up back in Objective C code. Therefore I am trying to add it to a structure that I already have, as a void * (void *videoDataOutputQueue;)
However, I have not found the right way to assign it without getting a EXC_BAD_ACCESS runtime error. Since dispatch_queue_t is a C++ object, can't I just use it's address?
declared in the interface for squarecamviewcontroller:
#interface SquareCamViewController : UIViewController <UIGestureRecognizerDelegate, AVCaptureVideoDataOutputSampleBufferDelegate,UIActionSheetDelegate>
{
AVCaptureVideoPreviewLayer *previewLayer;
AVCaptureVideoDataOutput *dataOutput;
AVCaptureVideoDataOutput *videoDataOutput;
dispatch_queue_t videoDataOutputQueue;
<other stuff>
}
later in the code:
- (void)setupAVCapture
{
<other stuff from the sample code>
MYSTRUCT myStruct = (MYSTRUCT)struct; // make a pointer to the structure
myStruct->videoDataOutputQueue = (void *)videoDataOutputQueue; <<<- bad access here at runtime
<other stuff>
}
Clearly this is not the right way and I don't understand what I am doing. I have some hints from other posts but I'm missing something.
Thanks,
Ken
You have made your question unnecessarily difficult to understand because the "code" you've presented has syntax errors. It's clearly not your real code, so we can't guess what's really supposed to be happening. For example, you use the struct reserved keyword as though it were a value.
Given where you say the bad access occurs, this has nothing to do with the dispatch queue. It looks like your myStruct variable is supposed to be a pointer to a structure of some kind but is just a garbage pointer. So, the attempt to assign a value to one of its fields ends up writing to an invalid memory address. It doesn't really matter what the nature of the field is.
The problem is apparently exactly in the code you omitted as "<other stuff from the sample code>". So, you need to show that. Indeed, you need to show your real code.
Beyond that, dispatch_queue_t is a C type. It's not specific to Objective-C. Therefore, you can use it across all C-based languages. There's no need to use a void*.
A dispatch queue, like all dispatch objects, is reference counted. If you're keeping a long-term reference to it, you need to make sure it stays alive. So, you need to retain it with dispatch_retain(). Likewise, you need to release it when you're done with it using dispatch_release(). (Don't forget to release the old value when you replace a reference you're keeping with another.)

C++: use of “().” and “()[].”

I am trying to understand the programming of Siemens scanner using C++ and given that my C++ skills are limited, I am having problems in understanding many parts of the code provided by the vendor.
Problem 1
For instance, the code uses reference (rMrProt) to object MrProt and notations (such as the use of use of (). and ()[].) are very confusing to me.
For instance:
ImageSamples = rMrProt.kSpace().baseResolution()
ImageSize = rMrProt.sliceSeries()[0].readoutFOV()
Some explanation of these statements would be appreciated.
All information regarding object MrProt are in “MrProt.h”, “MrProt.dll”, “MrProt.lib”. All these files have been shared at:
https://docs.google.com/open?id=0B0Ah9soYnrlIYWZkNDU2M2EtYTNmNC00YTc5LTllMzItYzIyMWU4M2ZhY2Fi
Problem 2
Also, I have been trying to read MrProt.dll and MrProt.lib without any success. Only now, I came to know of dumpbin. Any help would be appreciated.
Problem 3
Another confusion that I have is related to some part of MrProt.h itself. There is a statement in MrProt.h:
class __IMP_EXP MrProt: public MrProtocolData::MrProtDataDelegate
{
typedef MrProtocolData::MrProtDataDelegate BasicImplementation;
public:
MrProt();
MrProt(const MrProt& rSource);
…
….
}
Here, __IMP_EXP, I guess that it’s some compiler specific stuff.. some decoration etc. But, I still have no idea what to make of this.
Problem 1.
rMrProt.sliceSeries()[0].readoutFOV()
means
Take rMrProt's sliceSeries member and call that. Apparently, it returns an array-like object, something that can be indexed.
From the result, take the first element ([0]). That's some kind of object.
On that element/object, call readoutFOV.
Problem 2. You're not really supposed to read binary files. There should be documentation with them.
1)
ImageSamples = rMrProt.kSpace().baseResolution()
This is just method chaining. You call the method kSpace() on rMrPrto which returns an object, and you call baseResolution() on that object.
2) Those are binary files. What would you expect to see? To read them you'd have to be an expert in asm or at least know some low-level concepts.
3) __IMP_EXP is a common type of directive that tells the compiler that the class is either exported or imported.
It expands to _declspec(dllimport) or _declspec(dllexport), depending on whether the definition of the class is in the current module or another module.
identifier() is a method/function call
identifier[i] returns the i'th element in an array.
identifier()[i] returns the i'th element of the array returned by identifier()
I can only help on problem 1:
if the return value of rMrProt.kSpace() is a struct. instead of saving it to a struct and then access it's member you can directly access a member of his with rMrProt.kSpace().MemberName
same for rMrProt.sliceSeries() which I guess is returning an array. so rMrProt.sliceSeries()[0] will access the first value in the returning array.

How to allow your data structure to take in objects of any class - C++

How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.
Even better, you can specify what class of objects that ArrayList would store by doing...
new ArrayList()< whateverObject >
I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...
At the moment, I'm just using...
typedef whateverObject ItemType
at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, e.g. instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to simply use it for any object so...
How?!
Thanks.
Templates are the answer to your question.
Define your linked list as follows :
template<typename ItemType>
class ArrayList
{
// What's inside your class definition does not need to be changed
// Include your method definitions here and you'll be fine
};
The type to use is then ArrayList<WhateverObject>.
Use templates. It's a lot to explain so I'll just give you a link where it's explained much better than I'll ever be able to do here: C++ FAQ - Templates.
While you're at it, if you have the time, I suggest you read the whole FAQ, it's really a great resource!
If I have understood well what you ask, templates is what you want.
Take a look here:
http://www.cplusplus.com/doc/tutorial/templates/
In java you can do so, because all classes are inherited from one base class Object. In C++ you do not have it. The reason is that Object base class impose overhead for all objects, while C++ do not like any unnecessary overhead.
If you want to store any object - you can store "void *" data type. The question remained - what you will be able to do with objects, without the knowledge of the type? If you do know - you can cast to the needed type and use it. The practice described above is not safe, and templates are better in most cases.

C++ multi-dimensional data handling

Many times, I find myself having to define a container for multi-dimensional data.
Let's take an example: I have many Chips, each Chip has many Registers, each Register has many Cells, and each Cell has many Transistors.
At some stage of my C++ program I have to read this data, and later I have to use it.
I cannot use any external storage for this data: file, data-base, etc.
So, should I create some multi-dimensional STL container? A map of maps of vectors, or something like that... ?
Or should I create classes (structs) for each of them? Cell class that contains a vector of Transistors, and then a Register class that contains a vector of Cells, etc? But what if later I want to access my data by Transistor, and not by Chip?
Any other way?
Thank you
EDIT: Forgot to mention: I cannot use boost.
You need to map your domain.
So, should I create some multi-dimensional STL container? A map of maps of vectors, or something like that... ?
Each vector/map will contain objects of some type. That brings us to your next question :)
Or should I create classes (structs) for each of them?
Looks like that is what you need at the very least.
Cell class that contains a vector of Transistors, and then a Register class that contains a vector of Cells, etc?
Look at both has-a and is-implemented-in-terms-of designs.
But what if later I want to sort my data by Transistor, and not by Chip?
What data? You can always pass around comparators depending on the context. Also, ask yourself if you really need to expose the Transistor level details to someone working with a Chip. That'll help get started.
Implement full classes for them. Your code will be cleaner in the end.
Whenever I ignore this axiom, it comes back to haunt me. I implemented a hierarchical 3-tiered string collection in terms of std::pairs of std::strings and std:pairs. It was quick and simple, and when I had to replace one layer and then another with a class to contain extra attributes, it was surprisingly easy to do. But in the end, the code was a mess and I wasn't happy documenting it. Lesson learned again, and again, and again...
If you want to access your data along different "dimensions," you may be interested in boost::multi_index_container. I haven't used it myself, but it looks like it fits the bill.
As advised, I chose to implement full classes:
class Chip
{
map<RegisterLocation, Register> RegistersPerLocation;
public:
void AddRegisterPerLocation(RegisterLocation, Register);
};
class Register
{
map<CellLocation, Cell> CellsPerLocation;
public:
void AddCellPerLocation(CellLocation, Cell);
};
// etc..

Generating data structures by parsing plain text files

I wrote a file parser for a game I'm writing to make it easy for myself to change various aspects of the game (things like the character/stage/collision data). For example, I might have a character class like this:
class Character
{
public:
int x, y; // Character's location
Character* teammate;
}
I set up my parser to read in from a file the data structure with syntax similar to C++
Character Sidekick
{
X = 12
Y = 0
}
Character AwesomeDude
{
X = 10
Y = 50
Teammate = Sidekick
}
This will create two data structures and put them in a map<std::string, Character*>, where the key string is whatever name I gave it (in this case Sidekick and AwesomeDude). When my parser sees a pointer to a class, like the teammate pointer, it's smart enough to look up in the map to fetch the pointer to that data structure. The problem is that I can't declare Sidekick's teammate to be AwesomeDude because it hasn't been placed into the Character map yet.
I'm trying to find the best way to solve this so that I can have my data structures reference objects that haven't yet been added to the map. The two easiest solutions that I can think of are (a) add the ability to forward declare data structures or (b) have the parser read through the file twice, once to populate the map with pointers to empty data structures and a second time to go through and fill them in.
The problem with (a) is that I also can decide which constructor to call on a class, and if I forward declare something I'd have to have the constructor be apart from the rest of the data, which could be confusing. The problem with (b) is that I might want to declare Sidekick and AwesomeDude in their own files. I'd have to make my parser be able to take a list of files to read rather than just one at a time (this isn't so bad I guess, although sometimes I might want to get a list of files to read from a file). (b) also has the drawback of not being able to use data structures declared later in the constructor itself, but I don't think that's a huge deal.
Which way sounds like a better approach? Is there a third option I haven't thought of? It seems like there ought to be some clever solution to this with pointer references or binding or something... :-/ I suppose this is somewhat subjective based on what features I want to give myself, but any input is welcome.
When you encounter the reference the first time, simply store it as a reference. Then, you can put the character, or the reference, or whatever on a list of "references that need to be resolved later".
When the file is done, run through those that have references and resolve them.
Well, you asked for a third option. You don't have to use XML, but if you follow the following structure, it would be very simple to use a SAX parser to build your data structure.
At any rate, instead of referencing a teammate, each character references a team (Blue team in this case). This will decouple the circular reference issue. Just make sure you list the teams before the characters.
<team>Blue</team>
<character>
<name>Sidekick</name>
<X>12</X>
<Y>0</Y>
<teamref>Blue</teamref>
</character>
<character>
<name>Sidekick</name>
<X>10</X>
<Y>50</Y>
<teamref>Blue</teamref>
</character>
Personally, I'd go with b). Splitting your code into Parser and Validator classes, both operating on the same data structure. The Parser will read and parse a file, filling the data structure and storing any object references as their textual names, leaving the real pointer null in your structure for now.
When you are finished loading the files, use the Validator class to validate and resolve any references, filling in the "real" pointers. You will want to consider how to structure your data to make these lookups nice and fast.
Will said exactly what I was about to write. Just keep a list or something with the unsolved references.
And don't forget to throw an error if there are unsolved references once you finish reading the file =P
Instead of storing Character object in your map, store a proxy for Character. The proxy will than contain a pointer to the actual Character object when the object is loaded. The type of Character::teammate will be changed to this proxy type. When you read in a reference that is not already in your map, you create a proxy and use the proxy. When you load an character which you already have an empty proxy in the map, populate it with your newly loaded character. You may also want to add a counter to keep track of how many empty proxy you have in the map so you know when all referenced characters have been loaded.
Another layer of indirection....it always make programming easier and slower.
One option would be to reverse the obligation. The Map is responsible for filling in the reference
template<T> class SymbolMap // I never could rememeber C++ template syntax
{
...
/// fill in target with thing name
/// if no name yet, add it to the list of thing that will be name
void Set(T& target, std::string name);
/// define name as target
/// go back and fill in anything that needs to be name
void Define(T target, std::string name);
/// make sure everything is resolved
~SymbolMap()
}
that won't interact well with value/moving semantics but I suspect that not much will.