How can I convert this list of pairs into an object that contains an array of arrays?

bdbasinger

I have a list of pairs, and each pair holds two integer values. How can I convert this list of pairs into an object that contains an array of edges similar to what is presented in edges[] below? I have created a Graph class, but in order to use it, I need these pairs, which will be my edges, converted into an array of arrays, where each array within the array will hold one pair of two integer values.

This is my list containing the pairs of integer values:

list<pair<unsigned int, unsigned int> > myList;

This is the struct i created to hold the two edges:

struct Edge {
    int source
    int destination;
};

This array of edges is an example of what I want my list of pairs to be converted into:

Edge edges[] =
        {
            { 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 }
        };

If I need to be more specific about a particular part of the question, let me know and I will be happy to elaborate. Thanks

Armin Montigny

OP asked in comment to other answer on how possible implementations could look like.

In the original question it was stated:

  • OP has a list with data list<pair<unsigned int, unsigned int> > myList;
  • OP wants to use a struct with 2 members for usage in a graph
  • OP wants to convert the list into an array

I think OP's idea to have a struct to hold the values is a logical good approach. We have a Graph and the Graph contains several edges. Very reasonable.

So, let us define a class Graph and we will add an array of edges. But since we are in C++, we will not use a plain C-Style array, but a std::vector.

If we would use the vector of struct Edge, it could be used in the same way as the list:

std::vector<Edge> sameAsList{ { 0U, 1U }, { 1U, 2U }, { 2U, 0U }, { 2U, 1U } };

And we can easily convert the original list into such vector, even, if it is encapsulated in a Graph class. There are many possible implementations. I show the maybe most popular 3 versions.

  • Using iterators. That would be the pre C++11 solution
  • Range base for loop. Available since C++1. Easy to understand and easy to read
  • Transormation with std::transform. Maybe the "more modern" C++ solution

Please see

#include <vector>
#include <list>
#include <utility>
#include <algorithm>
#include <iostream>
#include <iterator>

// Define aliases. To make reading easier
using PairOfUint = std::pair<unsigned int, unsigned int>;
using ListOfPairs = std::list<PairOfUint>;

// Our struct for edges
struct Edge {
    Edge() {}
    Edge(unsigned int s, unsigned int d) : source(s), destination(d) {}
    friend std::ostream& operator << (std::ostream& os, const Edge& e) { return os << e.source << " " << e.destination; }

    unsigned int source{};
    unsigned int destination{};
};


class Graph
{
public:
    Graph() : edges() {}

    // 3 differnt conversion functions from list of pair to vector of struct. All have the same result
    void add1(ListOfPairs& lop);
    void add2(ListOfPairs& lop);
    void add3(ListOfPairs& lop);

    // Reset edges vector to empty 
    void clearEdges() { edges.clear(); }

    // Inserter. For this example, just print edges
    friend std::ostream& operator << (std::ostream& os, const Graph& g) {
        std::copy(g.edges.begin(), g.edges.end(), std::ostream_iterator<Edge>(os, "\n")); return os;
    }

protected:
    std::vector<Edge> edges{};
};

void Graph::add1(ListOfPairs& lop)
{
    for (ListOfPairs::const_iterator cIterLop = lop.cbegin(); cIterLop != lop.cend(); ++cIterLop)
        edges.emplace_back(Edge(cIterLop->first, cIterLop->second));
}

void Graph::add2(ListOfPairs& lop)
{
    for (const PairOfUint& poui : lop)
        edges.emplace_back(Edge(poui.first, poui.second));
}

void Graph::add3(ListOfPairs& lop)
{
    std::transform(lop.begin(), lop.end(), std::back_inserter(edges), [](const PairOfUint & poui) {
        return Edge(poui.first, poui.second); });
}


ListOfPairs myList{ { 0U, 1U }, { 1U, 2U }, { 2U, 0U }, { 2U, 1U } };

int main()
{
    Graph graph{};

    graph.add1(myList);
    std::cout << "\nVersion1 with iterators:\n" << graph;

    graph.clearEdges();
    graph.add2(myList);
    std::cout << "\n\nVersion2 with range based for:\n" << graph;

    graph.clearEdges();
    graph.add3(myList);
    std::cout << "\n\nVersion3 with std::transform for:\n" << graph;

    return 0;
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I create a new object that only contains the key/value pairs specified in an array?

How can I compare 2 arrays in python where one list contains an object in the other list

How can I convert an array with key-value pairs to an array with separate sub-arrays for the keys and values in PHP?

How do I convert a Json file (that contains a array) to a List (of a class object) C# Unity

how can i extract arrays from one array & convert them in object and put them in a new array?

How can I convert JSON object which contains an array into a single Struct instance

How can I convert an array to a list without using Arrays.asList() method or Java List Interface

how can i convert object into an array in javascript?

How can i convert array to SimpleXMLElement Object

How I can convert array to object in Javascript

Convert JavaScript array of 2 element arrays into object key value pairs

How can I convert an array of string arrays into an array of objects?

How can I convert .geojson file to a JavaScript object with nested arrays?

how can I read list of object of array

How i can convert array of object into array then a unique count of array

How can I convert a text file into a list of int arrays

How do I convert an object array to an object list

How to convert an array object to an array of arrays?

I have got a list of pairs how can i check whether the list contains a specific element or not.The list.contains function is always giving false

How i can to convert array to object of array in react?

how to convert this JavaScript object that contains an array to JSON?

I have an array of objects. Each object contains max and min key value pairs. How do I find the object that contains a predefined value?

How can I check the arrays in an array list - Python

How can I convert XML to an associative array and control what attributes to use as the name value pairs?

how do I convert an object to an array list in JS

How do I convert array to an array object and combine two arrays to a one array?

How can i convert Map of Strings and Object to a Map of Strings and List

How can I convert this object into a list and display on HTML?

How to convert a list of key value pairs to a dynamic object

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive