Question: I have a matrix (multidimensional array) and the index can only move downwards and diagonally as a result of a specific condition (movement is shown in the picture). How can we achieve this movement in C# or Java?

[![enter image description here](https://i.stack.imgur.com/cHQJE.png)](https://i.stack.imgur.com/cHQJE.png)

Answer: 
In your code, there could be two hash lookup in one query, one invoked in `count()` and the other invoked in `at()`. It is redundant, use `unordered_map::find` instead, see [here](https://en.cppreference.com/w/cpp/container/unordered_map/find).

Sample code:

```
const auto iter = Buffer.find(index);
if(iter != Buffer.end()) //Found something, so the return value is not end()
{
    return &(iter->first);
}
else return nullptr;

```

In my opinion, `unordered_map` is slow but not that slow, for 99.9% usage is fast enough. You may want to check whether you call this function (unnecessarily) too many times. Using other fast implementation is not free, it could bloat your code base, harm your application's compatibility with different host systems or so on. If you think `std::unordered_map` is unreasonably slow, it is almost always because you got somewhere wrong in your work. (either your estimation or your code implementation)

BTW, another thing to mention: You said T is a small data type right? then return its value instead of pointer to it, it is faster and safer.
One thing that strikes me as odd about your implementation is the following two lines:

```cpp
    if (!Buffer.count(index)) return nullptr;
    pair <T,long> &x{Buffer.at(index)};

```

This code is checking if the key exists, then throws away the result and searches for the same key again *with bounds checking* to boot. I think you'll find searching once with [`std::unordered_map<unsigned long, std::pair<T, long>>::find`](https://en.cppreference.com/w/cpp/container/unordered_map/find) and reusing the result to be preferable:

```cpp
    auto it = Buffer.find(index);
    if (it == Buffer.end()) return nullptr;
    auto& x = *it;

```