Dropping multiple datatypes in a vector in C ++

Let's say I have a vector full of points like this:

vector<Point3f> cluster_points

      

Now I am getting the distance between two points for each point in the vector. I want to store all this data in a container like below:

{distance, (both point index number from *cluster_points*)}  

      

eg.

{70.54,  (0,1)};
{98.485, (1,2)};
{87.565, (2,3)};
{107.54, (3,4)};

      

How can I do this in C ++ 11?

+3


source to share


3 answers


In C ++ 14:

struct DistanceBetweenPoints
{
    double distance = {};
    size_t p1 = {};
    size_t p2 = {};
};

std::vector<DistanceBetweenPoints> foo;
foo.push_back({ 70.54, 0, 1 });
//...

      



EDIT

Just like Kuri Giordano pointed out in the comments section, this is not supported in C ++ 11 because when you use initialization in a class, it becomes a non-POD type and you lose the aggregate construct. See his answer for C ++ 11 compatible solutions.

+4


source


Create a structure to store the things you want to keep. Give it the appropriate constructors.

struct distance_indexes_t
{
    double distance;
    size_t p1, p2;

    distance_indexes_t()
        : distance(), p1(), p2()
    {}

    distance_indexes_t( double distance, size_t p1, size_t p2 )
        : distance( distance ), p1( p1 ), p2( p2 )
    {}
};
distance_indexes_t di1; // zeros
distance_indexes_t di2{ 3.5, 4, 5 };

      

OR

struct distance_indexes_t
{
    double distance = 0;
    size_t p1 = 0, p2 = 0;

    distance_indexes_t() = default; // Not necessary, but nice for clarity.

    distance_indexes_t( double distance, size_t p1, size_t p2 )
        : distance( distance ), p1( p1 ), p2( p2 )
    {}
};
distance_indexes_t di1; // zeros
distance_indexes_t di2{ 3.5, 4, 5 };

      

Both will use the default copy constructor and the assignment operator. Moving the constructor and move operator doesn't matter here, but you'll get those defaults as well.



Alternatively, for C ++ 14:

struct distance_indexes_t
{
    double distance = 0;
    size_t p1 = 0, p2 = 0;
};
distance_indexes_t di1; // zeros
distance_indexes_t di2{ 3.5, 4, 5 };

      

Alternatively for C ++ 03 and earlier:

struct distance_indexes_t
{
    double distance;
    size_t p1, p2;
};
distance_indexes_t di1; // random content
distance_indexes_t di2{ 3.5, 4, 5 };

      

+2


source


Save the data to std::vector<std::tuple<float, std::pair<size_t, size_t>>>

.

No need for 5 or 20 or 50 new lines of code.

+2


source







All Articles