将const char转换为std::string作为标题。

问题描述 投票:0回答:2

我正在使用gnuplot。

在头文件中,我有以下功能。

void PlotPath(Gnuplot& gp, const char* title, bool first_plot = true, bool last_plot = true);

然后,在cpp文件中,

template <typename T>
void Path<T>::PlotPath(Gnuplot& gp, const char* title, bool first_plot, bool last_plot)
{
    std::vector<WaypointPath<T>> waypoints = GenerateWaypoints(5000);
    std::vector<std::pair<T, T>> plot_points(5000);

    for (size_t i = 0; i < waypoints.size(); ++i) {
        plot_points[i] = std::make_pair(waypoints[i].position[0], waypoints[i].position[1]);
    }

    if (first_plot) {
        gp << "plot" << gp.file1d(plot_points) << "with lines title '" << title << "',";
    } else {
        gp << gp.file1d(plot_points) << "with lines title '" << title << "',";
    }

    if (last_plot) {
        gp << std::endl;
    }
}

我想做的是不使用const char* title, 而是使用std: :string title. 所以,我做了如下的工作,它的工作原理是,但我想知道是否有更好的方法来实现这个任务。

template <typename T>
void Path<T>::PlotPath(Gnuplot& gp, const char* title, bool first_plot, bool last_plot)
{
    std::vector<WaypointPath<T>> waypoints = GenerateWaypoints(5000);
    std::vector<std::pair<T, T>> plot_points(5000);

    // Convert const char * to std::string
    std::string string_title = title;

    for (size_t i = 0; i < waypoints.size(); ++i) {
        plot_points[i] = std::make_pair(waypoints[i].position[0], waypoints[i].position[1]);
    }

    if (first_plot) {
        gp << "plot" << gp.file1d(plot_points) << "with lines title '" << string_title << "',";
    } else {
        gp << gp.file1d(plot_points) << "with lines title '" << string_title << "',";
    }

    if (last_plot) {
        gp << std::endl;
    }
}

在这里,我通过创建另一个变量将const char*转换为std::string。但是有没有一种方法可以将 std::string title 在函数参数本身?

我在这里所做的工作很好,但我只是在寻找一种更优雅的方法来解决这个问题。

谢谢你的期待。

c++ gnuplot
2个回答
2
投票

使你的参数 std::string. std::string 有一个构造函数,它以 const char* 所以这应该不是问题。


1
投票

没有必要转换。这段代码非常好用。

if (first_plot) {
    gp << "plot" << gp.file1d(plot_points) << "with lines title '" << title << "',";
} else {
    gp << gp.file1d(plot_points) << "with lines title '" << title << "',";
}
© www.soinside.com 2019 - 2024. All rights reserved.