我正在使用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
在函数参数本身?
我在这里所做的工作很好,但我只是在寻找一种更优雅的方法来解决这个问题。
谢谢你的期待。
使你的参数 std::string
. std::string
有一个构造函数,它以 const char*
所以这应该不是问题。
没有必要转换。这段代码非常好用。
if (first_plot) {
gp << "plot" << gp.file1d(plot_points) << "with lines title '" << title << "',";
} else {
gp << gp.file1d(plot_points) << "with lines title '" << title << "',";
}