Filling list inside object and accessing to it later - c++

I'm sorry if the title isn't very explicit, but I'll try to explain it better. I'm not very familiar with c++ and I'm using openFrameworks for the first time. I'm trying to do something that's probably quite easy, at least in other languages it is, but I'm not being able to do it :(
I have a class Video and inside it I have an object list<ofImage> keyFrames; and several methods to interact with it like the following:
void addKeyFrame(ofImage img) {
if(keyFrames.size() == 0) {
keyFrames.push_front(img);
}
else {
keyFrames.push_back(img);
}
}
list<ofImage> * getKeyFrames() {
list<ofImage> *list = &keyFrames;
return list;
}
void clearKeyFrames() {
keyFrames.clear();
}
In other class I have several Video objects and I have a function that uses addKeyFrame(ofImage img) to fill the list for each object. In the end of that function if I print the list size it is greater than zero.
Inside draw() function I iterate each Video object and I try to draw each image inside their keyFrame list, but the list is always empty and I just filled it with images... I'm using getKeyFrames() function to return a pointer to the list. How can it be empty if I just added objects to it in another function and if I verified that the size was greater than zero? And if I try to debug the application I feel even more lost lol.
Please tell me if you need anymore information and if you know what I'm doing wrong. Thanks!

Ok, A few little things:
1- You shouldn't check for empty lists (or any other STL containers) like this:
if(keyFrames.size() == 0)
This is faster and more "stylish":
if(keyFrames.empty())
2- You've created an unnecessary variable here:
list<ofImage> * getKeyFrames() {
list<ofImage> *list = &keyFrames;
return list;
}
You could do just:
list<ofImage> * getKeyFrames() {
return &keyFrames;
}
3- Pointers are not (most times) the best solution in C++. A reference is the most used substitute, but it would be even better in htis case if you returned an iterator:
list<ofImage>::iterator GetBeginIterator() {
return keyFrames.begin();
}
This way you could use the iterator just like a pointer, increasing it to iterate trough the frames and dereferencing it (with * operator)...

Related

Deleting and Reassigning a pointer from QList<Object *> to new Object using Iterator, is this right?

I have a QList and I'm trying to replace the objects in the list with new objects. The context is that I have a list of custom objects (the class name is "Conversation") to represent a list of group chats in a messaging platform. I use std::find_if to iterate through the list of pointers to find one with the right ID, and I want to take the pointer to that found object, deallocate it (delete?), and reassign that pointer to point at an object I generate with the "new" keyword. I think I'm doing this right but I'm not sure how to verify.
I tried a couple different iterations, ran into some issues where I realized I was using a const_iterator rather than just an iterator, so I couldn't modify any data. But I've fixed that and it seems like it's working, but I'm not positive.
Here's what I've got:
GroupChat *gc = new GroupChat(); // extends Conversation
// ...I update the member data here...
auto foundChat = std::find_if(conversations_.Conversations.begin2(),
conversations_.Conversations.end2(),
[this, gc](Conversation* o) { // my code to find the correct one...
}
if (foundChat != conversations_.Conversations.end()) {
auto c = (*foundChat);
delete c; // Is this right? Not positive...
//*foundChat = nullptr; // do I need this?
c = gc;
}
It seems like it's working but I'm worried about dangling pointers and incorrect memory deallocation/allocation. Could someone spot check me on this? Thanks for any help!

Return a pointer from a function to an object initialized in main()

I have been struggling with this problem for a few hours now and I've searched for every term that made sense to me. I might even have already read through a relevant answer but didn't recognize it as such because I'm a little confused by pointers.
So, I have a struct that is part of an object which is part of a chain of objects that is "anchored" (if you can call it that) in another object, which is itself part of a chain which is "anchored" in an anchor object initialized in main.
struct values
{
double val, ues;
}
class small
{
public:
values vals;
}
class big
{
public:
small *small_anchor;
}
values &getPointerToStruct(big *con)
{
values *return_vals;
if(con->small_anchor->vals.val==10)
return_vals=con->small_anchor->vals;
return (&return_vals);
}
int main()
{
values *main_values=NULL;//This is supposed to be pointing to the "vals" struct contained inside the "small" object.
big *big_anchor;
big_anchor = new big;
big_anchor->small_anchor = new small;
big_anchor->small_anchor->vals.val=10;
big_anchor->small_anchor->vals.ues=5;
main_values = getPointerToStruct(&big_anchor);//now main_values should be pointing to the "vals" struct
//I want to manipulate the value INSIDE the object itself
main_values.val++;
}
I have tried every combination of &, * and no prefix I could come up with, but nothing would give the result I was hoping for. "Closest" I got was copying "vals" (from inside the object) into "main_values" so that I could manipulate the values there, which isn't of any use to me, as I want to manipulate the SOURCE of the variables.
Also please note that I left out the process of scrolling down the chains to get to the object I was trying to reach and that "return_vals" seems arbitrary, but it happens that there are two possible candidates that could be the struct my program is looking for and the "return_vals" contains the best candidate found so far and is overwritten when a better one is found, or returned when the routine ends.
You wrote
values &getPointerToStruct(big *con)
{
values *return_vals;
if(con->small_anchor->vals.val==10)
return_vals=con->small_anchor->vals;
return (&return_vals);
}
where I think you wanted
values *getPointerToStruct(big *con)
{
values *return_vals = 0;
if(con->small_anchor->vals.val==10)
return_vals=&con->small_anchor->vals;
return (return_vals);
}
But the . in main_values.val++; is wrong anyway. You need to be consistent about whether you wanted to work with a values* or a values&. You could make all this work with a values& if you like, but then main_values should be a values& and not declared until you are ready to initialize it. return_vals would not be practical as a values& because of the stated requirement that the full code gives it a tentative address that is conditionally modified later. But even with return_vals as a values* you could still return a values& if that is what you preferred.

Copy structure without pointers

I'm trying to create an interface between physical components (Arduinos) and flight simulator in order to control and display simulator events from self-built parts. I have started learning C++ in school, but have never been quite keen on it.
Yet the library I use to communicate with my flight simulator is written in C++ (it's called SimConnect) and so is the SDK of my payware airplane. Therefore I figured it's probably easier to get back into it than creating wrappers or such for another programming language.
Every time I receive new data from the simulator, I pass it into the function ProcessNGXData:
PMDG_NGX_Data* previousData;
bool alreadyProcessed = false;
void ProcessNGXData(PMDG_NGX_Data *data)
{
if (!alreadyProcessed || data->LTS_TaxiSw != previousData->LTS_TaxiSw) {
if (data->LTS_TaxiSw)
printf("Taxi Lights: [ON]\n");
else
printf("Taxi Lights: [OFF]\n");
}
if (!alreadyProcessed) {
alreadyProcessed = true;
}
previousData = data;
}
In other programming languages, this would probably work fine, hence I tried to implement it like this. However, C++ pointers are a slight bit more complicated to me.
The condition data->LTS_TaxiSw != previousData->LTS_TaxiSw never evaluates to true. From my understanding, that is because both data and previousData are pointers to exactly the same structure and thus can never be different.
With my little knowledge and not much understanding of those pointers, how would I do this? Is there a way to copy the structure, so they can differ?
Thanks in advance.
Declare previousData like this:
PMDG_NGX_Data previousData;
(without the asterisk). Now, when you want to 'save' the structure, do this:
previousData = *data;
(right hand side has an asterisk). Note that this assumes that PMDG_NGX_Data is copy-able and a fixed size. If it's an interface or an abstract class, then this won't be possible. Perhaps the API gives you a "Clone" or "Copy" method you can call.
If PMDG_NGX_Data is not too big to copy every ProcessNGXData you can try this:
PMDG_NGX_Data previousData;
bool alreadyProcessed = false;
void ProcessNGXData(PMDG_NGX_Data *data)
{
if (!alreadyProcessed || data->LTS_TaxiSw != previousData.LTS_TaxiSw) {
if (data->LTS_TaxiSw)
printf("Taxi Lights: [ON]\n");
else
printf("Taxi Lights: [OFF]\n");
}
if (!alreadyProcessed) {
alreadyProcessed = true;
}
previousData = *data;
}
If it is too big, you can create a struct that will hold only the fields you need to compare and will be initialized by PMDG_NGX_Data and initialize that struct every ProcessNGXData.

Creating a vector in a method and setting it to a variable

OK so I an new to C++ and am fairly sure this should be a simple question if I can ask it right. Basically this is what I need to work:
printInfoFromVector(this->mycontroller.createVector)
This is the actual code I have:
vector<GasStation>& highPrices = this->myController.findHighestPrice();
this->findPrice(highPrices);
vector<GasStation>& findHighestPrice(){
The problem that I am having is that I can not get they types of highPrices and findHighestPrice() to match. Im fairly sure the problem is because I am passing by ref but I pretty sure that the right way to do it.
Can anyone tell me the correct way to write the assignment statement and the method head so that the types match?
If findHighestPrice is computing a new vector, then you should not return a reference, but an actual vector. Thus you would have:
vector<GasStation> findHighestPrice() { ... }
vector<GasStation> highPrices = this->myController.findHighestPrice();
For example, if you defined findHighestPrice as
vector<GasStation>& findHighestPrice() {
vector<GasStation> stations;
// ...
return stations;
}
then stations will be deallocated when the function returns and highPrices will be undefined.

Bitfields vs. Polymorphism for game map object attributes

This optimzation question has been bugging me for the last day.
In my program (a simple roguelike game), I use bitwise flags to store the attributes of map objects, such as if they are solid, or if they are rendered. However, I could accomplish the thing using polymorphism to return the appropriate value.
My question is, is either way significantly faster or slower than the other way when used in a linked list loop? Also, is one better practice than the other?
An example of the code:
XMapObject *List = ListStart;
while(List != NULL)
{
if(List->MapObjectFlags & MAPOBJECTFLAG_RENDER)
OR
if(List->Render())
{
return List->Type;
}
else
{
List = List->Next;
}
}
bool XMapObject::Render()
{
return 1;
}
Thanks.
A bitwise operation is always faster than a virtual function call.