954,483 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Managed C++ - Searching for an object in a generic list

Hi all,

to simplify my problem, I'll use a quick example.

Imagine I have a class of 'Cat' which has accessors for things like 'name', 'colour' and 'height'.

I then put these cats in a list

List<Cat^>^ catList;


I want to be able to search this list based on the properties of the cats. e.g. "Find me the cat called 'Ginger'".

I wish to use the List::Find Method to perform this search. http://msdn.microsoft.com/en-us/library/x0b5b5bc(v=VS.90).aspx

Something along the lines of this c# line, but in c++.net

String catName = "Ginger";
Cat myLocatedCat = catList.Find(delegate(Cat c) {return c.Name == catName; });


I tried to do something like this, but VS really wasn't happy with the delegate stuff. Clearly doing something wrong.

Any help - as always - will be greatly appreciated.

Smithy566
Newbie Poster
12 posts since Aug 2010
Reputation Points: 10
Solved Threads: 0
 

I found one way to do it, but I'm not very happy with the Find() method because it only passes one parameter to the comparison function (called a Predicate). If you want to find a specific cat I don't know how to do it without using some sort of global variable that contains the cat name. CLI/C++ does not permit String^ to be global. So the Find() method is not very useful in this case.

bool FindCat(MyCat::Cat^ c)
{
    return true;
}

int main(array<System::String ^> ^args)
{
    List<MyCat::Cat^>^ catList = gcnew List<MyCat::Cat^>;
    catList->Add(gcnew MyCat::Cat("one"));
    catList->Add(gcnew MyCat::Cat("two"));
    catList->Add(gcnew MyCat::Cat("three"));
    String^ catname = "two";
    MyCat::Cat^ myLocatedCat = catList->Find(
        gcnew Predicate<MyCat::Cat^>(FindCat) 
    );
    Console::WriteLine(L"Hello World");
    return 0;
}
Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: