I'm translating a part of code from C# to C++.
Here is the point I am :
Class Point
{
public int X;
public int Y;
}
const int MAX = 256;
public void ComputePoints(Byte[] image,
int width,
int height,
out List<Point>[] listPixels)
{
listPixels = new List<Point>[MAX];
//etc..
}
(I simplified this piece of code to only show interesting part).
My Question concern the out List<Point>[] listPixels
. I've try to translate this by :
public void ComputePoints(unsigned char[] image,
int width,
int height,
std::vector<Point> *listPixels[])
{
*listPixels = new std::vector<Point>[MAX];
//etc..
}
But I have error
Segmentation fault.
How can I write the simplest equivalent to out List<Point>[] listPixels
in C++ ?
Since List<Point>[]
is an array of lists, you could use a nested vector (vector of vector) to get the desired behaviour:
std::vector<std::vector<Point> >
Note that it could be important to add a space between the two >
's. Some compilers would not compile without.
Now you are able to pass the vector as reference like
void ComputePoints(... , std::vector<std::vector<Point> > &listPixels)
{
...
Why not return vector of vectors by value? In C++11 and newer it's fast and the code is easier to understand.
struct Point {
int x;
int y;
};
const int MAX = 256;
std::vector<std::vector<Point>> computePoints(const unsigned char image[], int width, int height) {
std::vector<std::vector<Point>> points(MAX);
// Here goes the code that does the calculations and fills 'points'.
return points;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With