and was commented as: use vector<vector<size_t> > to represent 2 dimensional matrices in C++ is an anti-pattern. The allocation wastes space and each access introduces an unnecessary memory access (which is expensive).
I came up with an alternative:
1 2 3 4 5 6 7 8 9 10 11
size_t strHandling(const std::string& s1, const std::string& s2)
{
std::vector<std::vector<size_t> > d(len1 + 1);
for (size_t i = 0; i < len1+1; i++)
d[i].resize(len2+1);
d[0][0] = 0;
for(unsignedint i = 1; i <= len1; ++i) d[i][0] = i;
for(unsignedint i = 1; i <= len2; ++i) d[0][i] = i;
// ...
}
Is there any difference between those two in terms of performace? Is there any better approaches in this situation to improve its performance?
That's not an alternative, that's the same thing written in a different way. It doesn't replace the vector<vector<...> > problem. The problem is that in an m*n matrix you end up with m+1 vectors each of which take some space apart from the things you pushed into them.
Notice that there is noting you can do with a 2d array that you couldn't do with a 1d one. arr2d[x][y] is equivalent to arr1d[x+y*width]. You can wrap it in a class to make it more comfortable.