【问题标题】:How to cin edges to each vertex? [closed]如何对每个顶点进行cin边缘? [关闭]
【发布时间】:2020-10-27 09:59:51
【问题描述】:

我对面向对象编程有点陌生。我正在尝试为每个顶点输入边,但对我来说似乎没有任何效果。

我想在 1 行将两个数字写入控制台。例如,如果 n = 4 和 m = 3,我可以在控制台中写入如下内容:
1 1
2 4
3 4

#include <iostream>
#include <vector>

using namespace std;

class Vertices
{
public:
    int color;
    vector<Vertices*> neighbours;
};

int main()
{
    int m, n;

    cin >> m; // edges
    cin >> n; // vertices
    cout << endl;

    Vertices*  vertices = new Vertices[n];


    for (int i = 0; i < m; i++)
    {
        // cin edges to each vertex
    }

    return 0;
}

【问题讨论】:

  • 为什么使用动态内存分配 (Vertices* vertices = new Vertices[n];) 而不是向量?你应该把它改成std::vector&lt;Vertices&gt; vertices(n);
  • 您应该考虑使用集合或无序集合。它会让事情变得更容易。
  • 提示:不要为单数事物使用复数名称。否则你会迷惑未来的自己。
  • 1 1 是什么意思?它是从第一个顶点到第一个顶点的边吗?边是有向的吗?

标签: c++ oop vector vertex


【解决方案1】:

您需要先从cin 中读取两个数字:

int src, dst;
cin >> src >> dst;

然后更新对应对象的邻居:

auto srcP = &vertices[src-1];
auto dstP = &vertices[dst-1];
srcP->neighbours.push_back(dstP);
if (src != dst) dstP->neighbours.push_back(srcP);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-14
    • 2021-04-03
    • 2022-01-16
    相关资源
    最近更新 更多