[英]How to return y value from vector 3 1D array
我有一个矢量3(x,y,z)1D动态阵列充满顶点位置。
如何在给定的x和z坐标处返回y值?
编辑::抱歉缺乏细节。
我正在使用c ++,在Visual Studio 2008中进行编译。向量是一个向量类,存储3个定义x,y和z变量的浮点值,它用于位置。
它就像Vector3 *数组;
array = new Vector3 [100];
大量的位置值被添加到数组中。
当您访问数组的成员以获取特定值时,它就像
阵列[0] .Y
但我想找到一个与特定x和z对应的y值
喜欢
GetY(float x,float z)
...
回归y;
我想你有类似的东西
struct Vec3D{
float x, y, z;
};
Vec3D vec3d_arr[20];
然后,为了得到你想要的东西,你需要迭代数组。
float GetYforXZ(Vec3D* arr, unsigned int length, float x_val, float z_val){
for(unsigned i=0; i < length; ++i){
if(arr[i].x == x_val && arr[i].z == z_val)
return arr[i].y;
}
}
int main(){
Vec3D arr[20];
// init arr
float y = GetYforXZ(arr,20,15.4f,23.3f);
}
编辑 :在你的评论:
#include <map>
#include <math>
using namespace std;
struct Vec3D{
float x, y, z;
};
const float float_eps = 1e-5;
struct float_wrapper{
float _value;
float_wrapper()
: _value(0.0f) {}
float_wrapper& operator=(float f){
_value = f;
return *this;
}
operator float() const{
return _value;
}
};
bool operator==(float_wrapper const& lhs, float_wrapper const& rhs){
float tmp = fabs(lhs._value - rhs._value);
return tmp < float_eps && tmp >= 0;
}
bool operator<(float_wrapper const& lhs, float_wrapper const& rhs){
return lhs._value < rhs._value;
}
typedef map< float_wrapper,float_wrapper > zy_map;
typedef map< float_wrapper,zy_map > xzy_map;
void init_vertex_mapping(xzy_map& a_map, Vec3D* arr, size_t length){
for(size_t i=0; i < length; ++i){
Vec3D& vertex = arr[i];
zy_map& zy = a_map[vertex.x];
zy[vertex.z] = vertex.y;
}
}
int main(){
xzy_map vertex_map;
Vec3D vertex_array[100] = { {0,0,0},{0,0,0},{0,0,0},{-3.14f,42.0f,-13.37f},{0,0,0} };
init_vertex_mapping(vertex_map, vertex_array, 100);
float y = vertex_map[-3.14f][-13.37f];
}
虽然我忘了的一个问题是float
的不准确性,所以也许你会遇到地图问题。 如果你这样做,请回复。 :)
编辑 :使用float_wrapper
添加了更安全的版本。
您只需要在数组中搜索具有给定x和z坐标的向量元素,并获取此元素的相应y值。
如果你的意思是,你的向量就像float vector[3];
然后vector[1]
引用数组中的第二个值,表示向量的Y坐标。
你觉得这段代码怎么样:
#include <iostream>
#include <algorithm>
using namespace std;
class Vector3
{
public:
int x;
int y;
int z;
enum SearchType
{
XY, YZ, XZ
};
static SearchType searchType;
Vector3(int x = 0, int y = 0, int z = 0)
: x(x), y(y), z(z)
{
}
bool operator == (const Vector3 & vec)
{
switch(searchType)
{
case XY: return (x == vec.x) && (y == vec.y);
case YZ: return (y == vec.y) && (z == vec.z);
case XZ: return (x == vec.x) && (z == vec.z);
}
return false;
}
};
Vector3::SearchType Vector3::searchType = XY;
int main()
{
Vector3 * array = new Vector3 [100];
array[57].x = 5;
array[57].y = 100;
array[57].z = 6;
Vector3::searchType = Vector3::XZ; // Specify find type as "XZ"
Vector3 * vec = std::find(array, array+100, Vector3(5,0,6));
if (vec != array+100)
{
cout << "Value for X == 5 and Z == 6 is in "
<< (vec-array) << " item and it eq " << (*vec).y;
}
}
请永远不要对未排序的数组/向量进行搜索。 即使它今天只有100个元素,它明天可能会变成100000个。 看看Wiki排序算法 ,其中一些很容易理解和实现。 然后看看Wiki Binary搜索 。 我会从快速排序开始,这也让你很清楚二进制搜索是如何工作的。 相信我,你以后会感谢我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.