The first one will return 5 when you do Value[2] because it is the value at index 2.
In the second, Value will be 2, because FindByKey looks through the array and finds an entry with the value you passed in. If the value passed to FindByKey wasn’t present in the array, you would crash when you dereferenced the nullptr return value.
Thanks for the Suggestion cmartel…
Do you mean the book Effective C++by Scott Meyers. I have been wanting to read a c++ book but couldn’t decide which one.
I knew about
const TArray<int32>& Value = *Pointer
but I didn’t want the reference of the whole
array when I just wanted the value of a single index.
A reference is as efficient as a pointer. Just like a pointer, it is simply referring to something by its address. The main difference with pointers is that a reference can only be created to a valid, existing type and cannot be changed once it is created. So even if your intent is to only refer to parts of an entire array, a reference is a better way to do it than a direct assignment which may end up causing a full copy.
I can highly recommend the method explains, and as he states, it is very efficient.
I can also add that getting the array by reference is the easiest to read when you return to your code at a later date.
**const** TArray<int32>& Value = *Pointer;
If you intend to change values of the array you can remove the const
Marc’s method (**Hi Marc!!! **) is the fastest to write if you only need to dereference the array once or twice, but if you refer to the array a lot, getting and setting values, its actually fastest typing-wise to do this:
TArray<int32>& IntArray = *ArrayPointer;
IntArray.Add(stuff);
UE_LOG(... IntArray[5]);
int32 Count = 0;
for(const int32& Each : IntArray)
{
Count += Each;
//array by ref so nice and clean to read!
}
**Efficiency**
**In all of the code above, no copies of the Array data are being made,** and you have full ability to set and get values from the original Array that you now have by reference.
Clarity
It is also as clean to read as if you had the original array, rather than a pointer to it that you then turned into reference.
**Personal Favorite For Clean Code**
Getting arrays by reference is one of my personal favorite ways to keep code clean while accessing array data stored in a faraway place from my current location in the code base.
Example:
```
void ASomeFarawayClass::UpdateNavData()
{
TArray<FNavData>& NavDataArray = YourCharacter->NavDataComponent->NavDataArray;
**//Now I can operate on the NavDataArray from a different location, without making any copies, and without typing that long ptr chain all the time!**
NavDataArray.Add(some new entry);
NavDataArray.RemoveAt(SomeIndex);
//Original array stored in the component of the Character has now been edited from somewhere else in a very easy-to-read way!
}
```
Enjoy!
Rama