• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3125
  • Last Modified:

Good example of CArray

I would like to have a good example (complete code) of the use of CArray, used to create a dynamic array:

How to declare it.
How to initialize it.
How to put new elements in it.
How to access its elements.

In my case, it would be an array of structs. Inside each struct I have only two CString fields.
1 Solution

// .h
// This is your array element class
class CTwoStrings
 CTwoStrings() {m_strOne=_T(""); m_strTwo=_T("");};
 ~CTwoStrings() {};

 CTwoStrings(const CTwoStrings& ref);
 CTwoStrings& operator=(const CTwoStrings& from);

 CString m_strOne;
 CString m_strTwo;

// .cpp
// and its implementation
CTwoStrings::CTwoStrings(const CTwoStrings& ref)
 *this = ref;

CTwoStrings& CTwoStrings::operator=(const CTwoStrings& from)
 m_strOne = from.m_strOne;
 m_strTwo = from.m_strTwo;

// Declare the array like this...
CArray<CTwoStrings, CTwoStrings&> array;

// and use it as ghim... has shown.
use CArray<CString,CString> or CArray(CString,const CString&> instead of CArray<CString,int>.

Read the docs on CArray to see what the two CArray template parameters mean.  You seem to think that making the second one 'int' means you'll be subscripting with an int.  This is not the case, CArrays ALWAYS subscript with an int.  The second arg is the type to use as args for any of the CArray functions.  It will usually be either the same type as the data (1st param) or a const& for the same type.  For simple data, same type is ok, for structs use the const&
Hey, Paulburns:

Shouldnt this return something?

CTwoStrings& CTwoStrings::operator=(const CTwoStrings& from)
 m_strOne = from.m_strOne;
 m_strTwo = from.m_strTwo;
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now