坐标的最佳容器
Best container for coordinates
我目前正试图从使用xlib的txt文件中拾取坐标,我一直在想什么是最好的容器用于这样的努力?我在想多维数组,因为我的程序将与三角形和最短路径算法一起工作,我也想问如何最好地填充使用扫描函数的容器,计划是使用嵌套循环来填充它。
编辑:我计划使用的txt文件是使用xlib函数绘制的三角形坐标列表,然后通过在界面上放置点,找到从用户定义的点到另一个点的最短路径,三角形作为障碍物。
int main(int argc,char *argv[])
{
int A,B;
int Trig[A][B];
FILE * pFile;
// First need to scan the file. Need to check if there's a file to look into first.
std::string pFilename = argv[1];
if (pFilename == ""){
cout << "Needs a Filename";
}
pFile = fopen(atoi(pFilename),"r");
// scanf(pFile,"%1s (%d,%d) (%d,%d) (%d,%d)",);
return 0;
}
如果这些是2D坐标,std::pair
将是一个很好的选择。
#include <utility>
int main()
{
std::pair<int, int> intCoordinates(5, 3);
std::cout << "x: " << intCoordinates.first;
std::cout << "y: " << intCoordinates.second << "n";
// -- hocus pocus, array of pairs, use it as normal C array
std::pair<int, int> arr[5];
}
当然你可以改变变量的类型。
如果你愿意,可以是<double, double>
甚至<double, int>
,这完全取决于你。
更多信息:http://www.cplusplus.com/reference/utility/pair/pair/
在这个或任何其他情况下,点结构体将完成工作:
struct Point {
int x, y;
Point(int a, int b) { this->x = a; this->y = b; }
};
int main()
{
Point p(2,3);
// ...
}
我们可能无法给你更多的建议,除非你给我们更多关于你的代码的信息。
我最近遇到了同样的问题,发现了那篇文章。我开始像这里建议的那样使用pair,但最后它不是那么容易使用和维护,所以我用一些实用程序操作符创建了我自己的Struct。
. hpp
struct Coordinates
{
std::size_t x;
std::size_t y;
Coordinates(std::size_t x, std::size_t y);
void add(std::size_t x, std::size_t y);
Coordinates operator+=(const Coordinates &coordinate);
Coordinates operator+(Coordinates coordinate);
};
. cpp
Coordinates::Coordinates(std::size_t x, std::size_t y) : x(x), y(y)
{
}
void Coordinates::add(std::size_t xAdd, std::size_t yAdd)
{
x += xAdd;
y += yAdd;
}
Coordinates Coordinates::operator+=(const Coordinates &coordinate)
{
add(coordinate.x, coordinate.y);
return *this;
}
Coordinates Coordinates::operator+(Coordinates coordinate)
{
return coordinate += *this;
}
你可以这样做:
Coordinates myPoint(4, 7);
myPoint += Coordinates(2, 3); // myPoint now contains x = 6 and y = 10
您也可以通过执行yourPoint.x
或yourPoint.y
访问字段x和y。
相关文章:
- 在C#中处理C++指针而不使用unsafe的最佳方法
- QGraphicsPolygonItem在拖动时未更新QPolygonF坐标
- 在C++中,将大的无符号浮点数四舍五入为整数的最佳方法是什么
- 实现无开销push_back的最佳方法是什么
- 在c代码之间共享数据的最佳方式
- 使用std::source_location报告错误的最佳实践
- 派生类销毁的最佳实践是什么
- 在C++中使用GDAL可以将图像的像素坐标转换为lat,long吗
- UE4-如何在给定4个屏幕坐标的情况下缩放纹理或材质
- 将寄存器设计成可由C和C++访问的外设的最佳实践
- 在两台机器之间进行时间戳的最佳c++chrono函数是什么
- 使用QQuickFramebufferObject时同步数据的最佳方式是什么
- 在C++中向零方向近似的最佳方法
- 使用不同的CRT将新的C++代码与旧的(二进制)组件隔离开来的最佳方法是什么
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 比较两个节点坐标的最佳方法是什么?
- 在 c++ 生成器中检测绘制线的窗口坐标的最佳方法
- 坐标的最佳容器
- 解析c++中坐标字符串的最佳方法