user1356791
user1356791

Reputation: 165

Storing current object in c++

I want to store the currently selected object (selected by mouse click) and then implement methods on this object. The currently selected object is chosen from an array:

for(int i=0; i<trackList.size(); i++)
{
    trackList[i].setSelected(false);
    if((trackList[i].isClicked(x,y)) && (!trackList[i].isSelected()))
    {
        trackList[i].setSelected(true);
        currentSelected = trackList[i];
    }
}

I am new to C++ and have read up on pointers etc. but I am struggling to understand where and how they should be used. Do I need to have my currentSelected object as a pointer to whatever trackList[i] is?

Can I then implement methods on this object using the pointer reference?

Many thanks

EDIT: trackList is storing a vector of Track objects:

std::vector<interface1::Track> trackList;

And currentSelected is storing a Track object which I want to apply methods to:

interface1::Track* currentSelected;

Upvotes: 0

Views: 252

Answers (1)

ruben2020
ruben2020

Reputation: 1549

You need to do:

 currentSelected = &(trackList[i]);

In order to assign the pointer the value of the address of trackList[i].

Another way is to use iterators, like this:

std::vector<interface1::Track> trackList;
std::vector<interface1::Track>::iterator it, currentSelected;
for (it = trackList.begin(); it != trackList.end(); it++)
{
    it->setSelected(false);
    if((it->isClicked(x,y)) && (!it->isSelected()))
    {
        it->setSelected(true);
        currentSelected = it;
    }
}

Later you can use currentSelected->setSelected(false); for both the pointer and iterator.

Upvotes: 1

Related Questions