tessellated wrote:
Hi all,
I want to iterate through a collection and at each item in the
collection access a particular property. In C# i know how to do this
easily, but with c++ I am a bit mystified Below is some sample code to
give you an idea of what i am trying to do.
SPGlobalAdmin * globAdmin = new SPGlobalAdmin();
SPVirtualServerCollection * servers = globAdmin->VirtualServers;
SPVirtualServer * vserver;
for (i = 0; i < servers->Count; i++)
{
//access properties of each vserver here
}
If this were c# I would just use a foreach loop like this
SPGlobalAdmin globAdmin = new SPGlobalAdmin();
foreach (SPVirtualServer vServer in globAdmin.VirtualServers)
{
string url = vServer.Url;
}
How to do this with c++?
If you're using C++/CLI (VC++ 2005) then you can use for each (note the
space) just as you would in C#. Otherwise, read on.
What kind of a collection is SPVirtualServersCollection? Each collection
class has some API to allow access to it's members. In the framework
classes, this API is usually expressed as IEnumerable, IList, ICollection,
IDictionary (or their generic equivalents in 2.0), or a combination of
these.
The C# foreach statement simply packages usage of the IEnumerable API into a
neat bit of syntactic sugar.
foreach (T t in C)
{
// stuff
}
is 100% equivalent to (and translated by the compiler literally to):
IEnumerator e = C.GetEnumerator();
while (e.MoveNext())
{
T t = (T)e.Current;
// stuff
}
You can use the same code in Managed C++ (VS2002/2003) to access framework
collections.
Of course, if you're talking about a C++ native collection such as a
std::vector, or on of the MFC collection classes, then they have different
APIs - but I gather that's not the kind of collection you're talking about.
-cd