[英]Converting const char to std::string for title
我正在使用 gnuplot。
在 header 文件中,我有以下 function:
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* 标题,而是使用 std::string 标题。 所以我所做的如下,它有效,但我想知道是否有更好的方法来完成这项任务。
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。 但是有没有办法在 function 参数本身中包含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 << "',";
}
C/C++ 方便的数据类型交换函数。 在这个 repo 中有所有 c++ 数据类型的便利功能,我把它们都写在 python 中。
使用这个回购:
https://github.com/azizovrafael/Simple-CPlusPlus
例子:
...
int main(){
int n = INT(INPUT("Write Some Text For Console Ex. (Enter: )"));
string str = STR(n);
return 0;
}
...
#simplecplusplus
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.