How to replace elements in an array of type T?

I have an Array2D<T> class that can take integer, reference types, etc. They are stored in this:
private T[] m_array = new T[width * height];
private T[] m_array = new T[width * height];
I have a method here that should replace elements.
void Replace(T from, T to)
{
}
void Replace(T from, T to)
{
}
I can't find any existing replace method. Any suggestions?
8 Replies
Omnissiah
Omnissiah2y ago
uhm wouldn't replace take also a index as argument? also by replace you mean assigning?
triplemocha
triplemochaOP2y ago
This would change any element that matched from and replace it with to.
occluder
occluder2y ago
Maybe m_array[Array.IndexOf(m_array, from)] = to;?
Omnissiah
Omnissiah2y ago
yeah, that but with a loop
occluder
occluder2y ago
void Replace(T from, T to)
{
int i;
while ((i = Array.IndexOf(m_array, from)) != -1)
{
m_array[i] = to;
}
}
void Replace(T from, T to)
{
int i;
while ((i = Array.IndexOf(m_array, from)) != -1)
{
m_array[i] = to;
}
}
like that maybe
triplemocha
triplemochaOP2y ago
It works, thanks!
Omnissiah
Omnissiah2y ago
from is kind of a reserved word just remember it
triplemocha
triplemochaOP2y ago
It's a contextual keyword.
Want results from more Discord servers?
Add your server