Member Avatar for Smithy566

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<T>::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.

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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.