I'm trying to make my Transpose function take pointers instead of std::arrays
. And the reason I want to do this is because then I can pass it a pointer or std::array
via the .data()
function.
Currently I have the following and it works using both 2D and 1D arrays for transposing in place or to a new array.. However, converting the below code to take pointers instead gives a memory access violation error.
Can someone explain the difference and why the below is not equal to my pointer versions (below this):
#include <iostream>
#include <array>
template<typename T, std::size_t Size>
void Transpose(std::array<T, Size> &Data)
{
int Width = sqrt(Size);
for (int I = 1; I < Width; ++I)
{
for (int J = 0; J < I; ++J)
{
std::swap(Data[I * Width + J], Data[J * Width + I]);
}
}
}
template<typename T, std::size_t Size>
void Transpose(std::array<std::array<T, Size>, Size> &Data)
{
for (int I = 0; I < Size; ++I)
{
for (int J = 0; J < I; ++J)
{
std::swap(Data[I][J], Data[J][I]);
}
}
}
However converting to the below does not work when I use a pointer :S
template<typename T>
void Transpose(T* Data, std::size_t Size)
{
int Width = sqrt(Size);
for (int I = 1; I < Width; ++I)
{
for (int J = 0; J < I; ++J)
{
std::swap(Data[I * Width + J], Data[J * Width + I]);
}
}
}
template<typename T>
void Transpose(T** Data, std::size_t Size)
{
for (int I = 0; I < Size; ++I)
{
for (int J = 0; J < I; ++J)
{
std::swap(Data[I][J], Data[J][I]);
}
}
}
Can anyone please explain the difference and why the T**
one does not work?