no existence
no existence

Reputation: 53

push back multiple types of data 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 distance between 2 points for each point in the vector. I want to store all these data in a container like below:

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

e.g.

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

How can I do this in C++11?

Upvotes: 3

Views: 2101

Answers (3)

Khouri Giordano
Khouri Giordano

Reputation: 796

Make a structure to hold the things you want to hold. Give it 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 assignment operator. Move constructor and move operator don't matter here, but you'll get those defaults too.

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

Upvotes: 2

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Store the data in a std::vector<std::tuple<float, std::pair<size_t, size_t>>>.

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

Upvotes: 2

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 Khouri Giordano noted in the comments section, this isn't supported in C++11 because when using in-class initialization, it becomes a non-POD type and you lose aggregate construction. See his answer for C++11 compatible solutions.

Upvotes: 4

Related Questions