我正在尝试使用自己的分配器来测量C ++ std::set
中的内存使用情况。不幸的是,我在链接时遇到错误。为了简化问题,我有以下程序:
#include<set>
#include<vector>
#include<memory>
//using Container = std::vector<int, std::allocator<int>>;
using Container = std::set<int, std::allocator<int>>;
int main() {
Container container;
container.push_back(4711);
container.insert(4711);
return 0;
}
结果可以在wandbox https://wandbox.org/permlink/R5WcgSvSWiqstYxL#wandbox-resultwindow-code-body-1
中找到我尝试过gcc 6.3.0,gcc 7.1.0,clang 4.0.0和clang 6.0.0HEAD。在所有情况下,我在使用std::set
时都会出错,但在使用std::vector
时则会出错。
如何声明我的设置使用分配器?
我想使用C ++ 17,但C ++ 14中的答案也很好。
答案 0 :(得分:5)
您应该更仔细地查看std::set
的模板参数:
<!DOCTYPE html>
<html>
<head>
<title>Snake Game</title>
</head>
<body>
<script type="text/javascript">
var s;
var scl = 20;
var food;
function setup() {
createCanvas(600, 600);
s = new Snake();
frameRate(10);
pickLocation();
}
function pickLocation() {
var cols = floor(width / scl);
var rows = floor(height / scl);
food = createVector(floor(random(cols)), floor(random(rows)));
food.mult(scl);
}
function draw() {
background(51);
if (s.eat(food)) {
pickLocation();
}
s.death();
s.update();
s.show();
fill(255, 0, 100);
rect(food.x, food.y, scl, scl);
}
function keyPressed() {
if (keyCode === UP_ARROW) {
s.dir(0, -1);
} else if (keyCode === DOWN_ARROW) {
s.dir(0, 1);
} else if (keyCode === RIGHT_ARROW) {
s.dir(1, 0);
} else if (keyCode === LEFT_ARROW) {
s.dir(-1, 0);
}
}
function Snake() {
this.x = 0;
this.y = 0;
this.xspeed = 1;
this.yspeed = 0;
this.total = 0;
this.tail = [];
this.eat = function (pos) {
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.total++;
return true;
} else {
return false;
}
}
this.dir = function (x, y) {
this.xspeed = x;
this.yspeed = y;
}
this.death = function () {
for (var i = 0; i < this.tail.length; i++) {
var pos = this.tail[i];
var d = dist(this.x, this.y, pos.x, pos.y);
if (d < 1) {
this.total = 0;
this.tail = [];
}
}
}
this.update = function () {
for (var i = 0; i < this.tail.length - 1; i++) {
this.tail[i] = this.tail[i + 1];
}
if (this.total >= 1) {
this.tail[this.total - 1] = createVector(this.x, this.y);
}
this.x = this.x + this.xspeed * scl;
this.y = this.y + this.yspeed * scl;
this.x = constrain(this.x, 0, width - scl);
this.y = constrain(this.y, 0, height - scl);
}
this.show = function () {
fill(255);
for (var i = 0; i < this.tail.length; i++) {
rect(this.tail[i].x, this.tail[i].y, scl, scl);
}
rect(this.x, this.y, scl, scl);
}
}
setup();
pickLocation();
draw();
keyPressed();
Snake();
</script>
</body>
<html>
当您写:template<
class Key,
class Compare = std::less<Key>,
class Allocator = std::allocator<Key>
> class set;
时,您说要使用分配器来比较密钥。这没有任何意义,因为分配器不像比较器那样可调用,编译器会抱怨。
您需要明确提供std::set<int, std::allocator<int>>
参数:
Compare