Ahmed Sayed wrote:
I have been wondering for a while how can I use C++
not just C++11 best practices specially “for loops”
With Delphi classes Like (TStrings, TFields, TDataSet. Etc)
so that I can produce a faster loop like his one:
No, because you don't have direct access to their internal data. You
don't have that issue with a DynamicArray since you can access its
internal array directly and then use pointer iteration over it, just
like with a std::vector.
//instead if this for DynamicArray SLOW
for (int i = 0; i < darr.Length; i++)
{
darr[i];
}
That is slow because DynamicArray::operator[] performs bounds checking.
std::vector::operator[] does not (but std::vector::at() does).
//instead if this for vector SLOW
for (int i = 0; i < vint.size(); i++)
{
vint[i];
}
//use this FASTER
const int *ptr = (size > 0) ? &vint.front() : NULL;
for (int i = 0; i < size; ++i)
{
ptr[i];
}
For a std::vector, that is not MUCH faster. All you are really saving
is 2 very minimal overhead CALL statements and not much code logic.
Now how can I use the same technique but with
TStrings, TFields, TDataSet or any delphi class
that can be iterated?
You can't.
HOWEVER, in C++Builder 2006 and later, Delphi container classes
implement enumerators, which you CAN use in C++, for example:
TStrings *list = ...;
TStringsEnumerator *enumerator = list->GetEnumerator();
while (enumerator->MoveNext()) {
String value = enumerator->Current;
...
}
delete enumerator;
A similar convention works for other enumerable Delphi classes,
including the ones you mentioned.
And, if you are using C++11, those classes can also be used in various
iterator-based operations, like range-for loops and STL algorithms:
http://docwiki.embarcadero.com/RADStudio/en/C%2B%2B_Iterator_Support_for_Delphi_Enumerable_Types_and_Containers
--
Remy Lebeau (TeamB)
Connect with Us