std::transform and C style arrays

This topic is 4407 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

A few questions. 1) Is it ok to use a C style array with std::transform? The following code works for me, but I wanted to make sure it's not a case where it just happens to work with my compiler, but will break with a different C++ implementation.
// m_Data is defined float m_Data[9]

CMatrix3x3& CMatrix3x3::operator+=(const CMatrix3x3 &rhs)
{
for (int i = 0; i < 9; ++i)
m_Data += rhs.m_Data;

return *this;
}

CMatrix3x3& CMatrix3x3::operator+=(const CMatrix3x3 &rhs)
{
std::transform (rhs.m_Data, rhs.m_Data + 9, m_Data, m_Data, std::plus<float>() );

return *this;
}

2) Is there any reason I should prefer either of the 2 implementations above? 3) Should I be using a std::vector or is a 3x3 matrix a case where a C style array is acceptable?

Share on other sites
Both should work just fine, but in this case, I think the C-like version is more readable (and more reasonable), since it such a simple mathematical concept. Still, in Release mode, this should compile to the exact same code.

Edit: fixed typo.

[Edited by - Kippesoep on December 29, 2005 1:27:40 PM]

Share on other sites
Quote:
 Original post by KippesoepBoth should work just fine, but in this case, I think the C-like version is more readable (and more reasonable), since it such a simple mathemetical concept. Still, in Release mode, this should compile to the exact same code.

Agreed.

OP:

@1: The iterator concept is very intentionally modeled (in terms of physical syntax at least) on pointers, so that you can do just that very kind of thing.

@2: I would prefer the former for readability in this case.

@3: A C style array is quite acceptable here - no need for the dynamic allocation (and increased pagefaults) associated with std::vector since the size is fixed. If you want something more "SC++L-like", there's Boost.Array, which would allow you to write your code like this:

// m_Data is defined as boost::array< float , 9 > m_Data;CMatrix3x3& CMatrix3x3::operator+=(const CMatrix3x3 &rhs){  std::transform (rhs.m_Data.begin(), rhs.m_Data.end(), m_Data.begin(), m_Data.begin(), std::plus<float>() );  return *this;}

The first snippet would also still work (as you can see, boost::array implements operator[], along with all those other goodies)

Share on other sites
Quote:
 Original post by MaulingMonkey@2: I would prefer the former for readability in this case.

That's pretty much how I feel, just wanted to make sure the examples above were essentially equivalent - and that I wouldn't be doing anything horribly wrong by plugging a C style array into std::transform.

Thanks to everyone for the help.