数组、模板类vector对象、模板类array对象

#include <iostream>
#include <vector>
#include <array>
int main()
{
	using namespace std;
	double a1[4]={1.2,2.4,3.6,4.8};

	vector<double> a2(4);
	a2[0]=1.0/3.0;
	a2[1]=1.0/5.0;
	a2[2]=1.0/7.0;
	a2[3]=1.0/9.0;

	array<double,4> a3={3.14,2.72,1.62,1.41};
	array<double,4> a4;
	a4=a3;

	cout<<" a1[2]: "<<a1[2]<<" at "<<&a1[2]<<endl;
	cout<<" a2[2]: "<<a2[2]<<" at "<<&a2[2]<<endl;
	cout<<" a3[2]: "<<a3[2]<<" at "<<&a3[2]<<endl;
	cout<<" a4[2]: "<<a4[2]<<" at "<<&a4[2]<<endl;

	a1[-2]=20.2;
	cout<<" a1[-2]: "<<a1[-2]<<" at "<<&a2[-2]<<endl;
	cout<<" a3[2]: "<<a3[2]<<" at "<<&a3[2]<<endl;
	cout<<" a4[2]: "<<a4[2]<<" at "<<&a4[2]<<endl;
	return 0;
}
//a1[-2]=20.2; 找到a1位置 前移两个单位 是不安全的代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用模板类函数来实现KD树时,可以按照以下方式编写代码: ```cpp #include <iostream> #include <vector> template <typename T, size_t K> struct KDNode { std::array<T, K> point; KDNode<T, K>* left; KDNode<T, K>* right; KDNode(const std::array<T, K>& p) : point(p), left(nullptr), right(nullptr) {} }; template <typename T, size_t K> class KDTree { private: KDNode<T, K>* root; KDNode<T, K>* buildTree(std::vector<std::array<T, K>>& points, size_t depth) { if (points.empty()) { return nullptr; } size_t axis = depth % K; auto cmp = [axis](const std::array<T, K>& a, const std::array<T, K>& b) { return a[axis] < b[axis]; }; std::sort(points.begin(), points.end(), cmp); size_t median = points.size() / 2; KDNode<T, K>* node = new KDNode<T, K>(points[median]); node->left = buildTree(std::vector<std::array<T, K>>(points.begin(), points.begin() + median), depth + 1); node->right = buildTree(std::vector<std::array<T, K>>(points.begin() + median + 1, points.end()), depth + 1); return node; } public: KDTree() : root(nullptr) {} void build(std::vector<std::array<T, K>>& points) { root = buildTree(points, 0); } }; ``` 使用示例代码: ```cpp int main() { std::vector<std::array<int, 2>> points{{3, 6}, {17, 15}, {13, 15}, {6, 12}, {9, 1}, {2, 7}, {10, 19}}; KDTree<int, 2> tree; tree.build(points); return 0; } ``` 以上代码实现了一个简单的KD树,其中`T`表示点的坐标数据类型,`K`表示点的维度。`KDNode`结构体表示KD树的节点,`KDTree`类则表示整个KD树的数据结构。`buildTree`函数用于递归地构建KD树,`build`函数用于构建整个KD树。 注意:以上代码只是一个简单的示例,实际应用中可能需要根据具体情况进行更多的优化和功能扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值