You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LEMON C++库的graphToEps中为网格图添加边权重标注?

解决LEMON graphToEps显示边权重的问题

我之前也碰到过一模一样的需求,LEMON的graphToEps确实没有直接接收整数权重的edgeTexts重载,但我们可以通过两种简单方式实现边权重的显示:

方法一:创建字符串类型的边映射

先把整数权重转换成字符串格式的边映射,再传递给edgeTexts方法:

#include <lemon/grid_graph.h>
#include <lemon/eps.h>
#include <iostream>
#include <string>

using namespace lemon;

int main() {
    // 创建图并初始化映射
    GridGraph g = GridGraph(5, 5);
    GridGraph::NodeMap<Point> coords(g);
    GridGraph::EdgeMap<int> weights(g, 1);
    // 新增字符串类型的边权重映射
    GridGraph::EdgeMap<std::string> weightTexts(g);

    // 为graphToEps设置节点位置
    for(GridGraph::NodeIt u(g); u != INVALID; ++u ) {
        coords[u] = g.pos(u);
    }

    // 将整数权重转换为字符串
    for(GridGraph::EdgeIt e(g); e != INVALID; ++e) {
        weightTexts[e] = std::to_string(weights[e]);
    }

    std::cout << "Create 'graph.eps'" << std::endl;
    graphToEps(g,"graph.eps")
        .coords(coords)
        .title("Sample .eps figure")
        .edgeTexts(weightTexts)  // 绑定边权重文本
        .run();

    return 0;
}

方法二:用Lambda表达式动态生成文本

如果不想额外创建字符串映射,可以直接用Lambda表达式实时转换权重为字符串,graphToEps支持接收函数对象作为edgeTexts的参数:

#include <lemon/grid_graph.h>
#include <lemon/eps.h>
#include <iostream>
#include <string>

using namespace lemon;

int main() {
    // 创建图并初始化映射
    GridGraph g = GridGraph(5, 5);
    GridGraph::NodeMap<Point> coords(g);
    GridGraph::EdgeMap<int> weights(g, 1);

    // 为graphToEps设置节点位置
    for(GridGraph::NodeIt u(g); u != INVALID; ++u ) {
        coords[u] = g.pos(u);
    }

    std::cout << "Create 'graph.eps'" << std::endl;
    graphToEps(g,"graph.eps")
        .coords(coords)
        .title("Sample .eps figure")
        .edgeTexts([&](const GridGraph::Edge& e) {
            return std::to_string(weights[e]);
        })  // 动态生成边权重文本
        .run();

    return 0;
}

额外优化:调整边标签样式

如果默认的标签位置、字体不够理想,还可以用edgeTextStyle自定义样式:

graphToEps(g,"graph.eps")
    .coords(coords)
    .title("Sample .eps figure")
    .edgeTexts(weightTexts)
    .edgeTextStyle(EpsStyle().color(Color::RED).fontSize(8).offset(Point(0, 5)))
    .run();

这样就能在每条边的指定位置清晰显示权重值了。

内容的提问来源于stack exchange,提问作者sourLemons

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 19:42:49