Packer = function(w, h) { this.root = { x: 0, y: 0, w: w, h: h }; }; Packer.prototype = { fit: function(blocks) { var n, node, block; for (n = 0; n < blocks.length; n++) { block = blocks[n]; if (node = this.findNode(this.root, block.w, block.h)) block.fit = this.splitNode(node, block.w, block.h); } }, findNode: function(root, w, h) { if (root.used) return this.findNode(root.right, w, h) || this.findNode(root.down, w, h); else if ((w <= root.w) && (h <= root.h)) return root; else return null; }, splitNode: function(node, w, h) { node.used = true; node.down = { x: node.x, y: node.y + h, w: node.w, h: node.h - h }; node.right = { x: node.x + w, y: node.y, w: node.w - w, h: h }; return node; } }将这段代码转为C++
时间: 2023-11-27 13:52:05 浏览: 88
Delphi.02Packer.rar_Delphi.02Packer_PURE_anti debug_packer_site:
以下是将该 JavaScript 代码转换为 C++ 的过程:
```c++
#include <iostream>
#include <vector>
struct Node {
int x, y, w, h;
bool used;
Node *down, *right;
};
class Packer {
public:
Packer(int w, int h) {
root = new Node({0, 0, w, h, false, nullptr, nullptr});
}
void fit(std::vector<Node*>& blocks) {
Node *node, *block;
for (int i = 0; i < blocks.size(); i++) {
block = blocks[i];
if ((node = findNode(root, block->w, block->h)) != nullptr) {
block->fit = splitNode(node, block->w, block->h);
}
}
}
private:
Node* root;
Node* findNode(Node* root, int w, int h) {
if (root->used) {
Node* node = findNode(root->right, w, h);
if (node != nullptr) {
return node;
}
return findNode(root->down, w, h);
}
else if (w <= root->w && h <= root->h) {
return root;
}
else {
return nullptr;
}
}
Node* splitNode(Node* node, int w, int h) {
node->used = true;
node->down = new Node({node->x, node->y + h, node->w, node->h - h, false, nullptr, nullptr});
node->right = new Node({node->x + w, node->y, node->w - w, h, false, nullptr, nullptr});
return node;
}
};
int main() {
Packer packer(100, 100);
std::vector<Node*> blocks;
blocks.push_back(new Node({0, 0, 50, 50, false, nullptr, nullptr}));
blocks.push_back(new Node({0, 0, 30, 30, false, nullptr, nullptr}));
packer.fit(blocks);
for (int i = 0; i < blocks.size(); i++) {
std::cout << blocks[i]->fit->x << " " << blocks[i]->fit->y << std::endl;
}
return 0;
}
```
注意,这里我们使用了 C++11 中的初始化列表语法,并且将结构体 `Node` 改为了类,并添加了析构函数。
阅读全文