我有一个对的列表,每对包含两个整数值。如何将此对列表转换为包含与下面的边 [] 中显示的边类似的边数组的对象?我创建了一个 Graph 类,但为了使用它,我需要将这些对(将是我的边)转换为数组数组,其中数组中的每个数组将保存一对两个整数值。
这是我的包含整数值对的列表:
list<pair<unsigned int, unsigned int> > myList;
这是我创建的用于保存两条边的结构:
struct Edge {
int source
int destination;
};
这个边数组是我希望将我的对列表转换为的示例:
Edge edges[] =
{
{ 0, 1 }, { 1, 2 }, { 2, 0 }, { 2, 1 }
};
如果我需要更具体地说明问题的特定部分,请告诉我,我很乐意详细说明。谢谢
OP 在评论其他答案时询问了可能的实现方式。
在最初的问题中是这样说的:
list<pair<unsigned int, unsigned int> > myList;
我认为 OP 拥有一个结构来保存值的想法是一个合乎逻辑的好方法。我们有一个图,图包含几个边。非常合理。
所以,让我们定义一个 Graph 类,我们将添加一个边数组。但是由于我们使用的是 C++,因此我们不会使用普通的 C 样式数组,而是使用std::vector
.
如果我们使用 struct Edge 的向量,它可以以与列表相同的方式使用:
std::vector<Edge> sameAsList{ { 0U, 1U }, { 1U, 2U }, { 2U, 0U }, { 2U, 1U } };
并且我们可以轻松地将原始列表转换为这样的向量,即使它被封装在一个 Graph 类中。有许多可能的实现方式。我展示了可能最受欢迎的 3 个版本。
std::transform
。也许是“更现代”的 C++ 解决方案请参阅
#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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句