Re: Java's ArrayList.contains counterpart of MFC CArray?
"divya_rathore" <divyarathore@gmail.com> ha scritto nel messaggio
news:de6e11b7-d242-4dcc-89fd-94edc21d70c6@g27g2000yqn.googlegroups.com...
I want to check if a particular CPoint exists in a large CArray as
defined above.
CArray doesn't have an inbuilt member function that would do that. So
was looking for existing techniques before writing afresh.
Assuming that you are sure to use CArray and not other data structures (like
std::set suggested by Goran), you may use a template function something like
this (which is a thin wrapper on STL find()):
<code>
//
// Check if 'value' is contained in array 'arr'.
//
template <typename T>
bool Contains(
const CArray<T, T> & arr,
const T & value
)
{
const INT_PTR count = arr.GetSize();
const T * pTest = std::find( &arr[0], &arr[0] + count, value );
if ( pTest != (&arr[0] + count) )
{
return true;
}
else
{
return false;
}
}
</code>
Then you can use this Contains() function like this:
<code>
void CTestMfc1Dlg::OnBnClickedButton1()
{
CArray<CPoint, CPoint> arr;
arr.Add( CPoint(2, 1) );
arr.Add( CPoint(3, 1) );
arr.Add( CPoint(2, 10) );
arr.Add( CPoint(1, 1) );
// CPoint pointToFind(2, 10);
CPoint pointToFind(10, 20);
if ( Contains(arr, pointToFind) )
{
AfxMessageBox(TEXT("Contained."));
}
else
{
AfxMessageBox(TEXT("Not contained."));
}
}
</code>
You should #include <algorithm> in your "StdAfx.h" header to use STL find.
HTH,
Giovanni