Logo Questions Linux Laravel Mysql Ubuntu Git Menu

C++ how to implement an array of list




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];


(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];


But I have error

Segmentation fault.

How can I write the simplest equivalent to out List<Point>[] listPixels in C++ ?

like image 345
A.Pissicat Avatar asked Mar 07 '23 19:03


2 Answers

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)
like image 195
Fruchtzwerg Avatar answered Mar 29 '23 22:03


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;
like image 29
navyblue Avatar answered Mar 29 '23 23:03