C ++ how to implement a list array

I translated part of the code from C # to C ++.

Here is my question:

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 show only the interesting part).

My question is concerned out List<Point>[] listPixels. I tried to translate this:

public void ComputePoints(unsigned char[] image,
                          int width, 
                          int height,
                          std::vector<Point> *listPixels[])
{
    *listPixels = new std::vector<Point>[MAX];

    //etc..
}

But I have a mistake

Segmentation error.

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

+4
source share
3 answers

Since List<Point>[]this is an array of lists, you can use a nested vector (vector of a vector) to get the desired behavior:

std::vector<std::vector<Point> >

Note that it may be important to add a space between the two >. Some compilers will not compile without.

Now you can pass the vector as a link, for example

void ComputePoints(... , std::vector<std::vector<Point> > &listPixels)
{
   ...
+6
source

std:: array.

new ++, , #/java ++.

( ), , , (std:: unique_ptr, std:: shared_ptr), ++, , , .

#include <list>
#incldue <array>

const int MAX = 256;
std::array<std::list<Point>, MAX> array_list;

def :

using MyContainer = std::array<std::list<Point>, 256>;
MyContainer array_list;

would be one way to have a array of lists

, std::vector ( ),

pre-++ 11 ( ) std::vector std:: array, , , std::vector C.

, C-: :

std::list<Point> my_list_array[MAX];

, :

std::list<Point>* my_list_array = new std::list<Point>[MAX];
//but don't forget about the delete[]!
+1

Why not return the vector of vectors by value? In C ++ 11 and newer, this is 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;
}
+1
source

Source: https://habr.com/ru/post/1687645/


All Articles