-2

in C# I had the following class:

 public class PixelInfo
{
    public DateTime CreatedTime;
    public float x;
    public float y;
}

with the following code I was able to save multiple pixels:

 private readonly List<PixelInfo> _pixels = new List<PixelInfo>();

foreach...
{
    _pixels.Add(new PixelInfo()
    {
        CreatedTime = DateTime.Now,
        x = xx,
        y = yy,
    });
}

Now I want to do the same in C++ and I tried it the following way:

std::list<PixelInfo> _pixels = {};
_pixels.push_back(new PixelInfo()
{
    ...
});

but this gives me an error. How can I save a List of multiple pixels using the class properties?

nexo sharp
  • 19
  • 5
  • 1
    new returns a heap allocated memory `pointer`, just use `PixelInfo() { /* code */ }` – Darth-CodeX May 12 '22 at 16:21
  • 1
    Please invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282) if you need to program in C++. C++ and C# are *very* different languages. – Some programmer dude May 12 '22 at 16:26

1 Answers1

3

First of all, a C# List is not the same as a C++ std::list. In C# a list is more like a C++ std::vector, and it's std::vector that should be the default container to use.

Secondly, in C++ you don't have to use new to create objects. In fact, new in C++ creates an object somewhere in memory and returns a pointer to it. The result of new PixelInfo() will have the type PixelInfo* which is quite different from PixelInfo.

And thirdly, you can't initialize members of classes or structures in C++ like you do in C#.

I recommend using the emplace_back function of std::vector to create and initialize the objects:

std::vector<PixelInfo> _pixels;

// ...

_pixels.emplace_back(some_date_and_time, x, y);
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I'd have one more question. If I do "for (auto pixel : _pixels)" how can i remove the current object from the list in each iteration. using "_pixels.erase(pixel);" doesn't work? – nexo sharp May 12 '22 at 16:54
  • @nexosharp: use the `erase_if` member function and pass your processing code as a lambda.... the vector will call it for each item, and its return value controls whether to erase or keep the item. – Ben Voigt May 12 '22 at 17:02