我目前正在使用 C++ 开发一个 kinect 项目。我在 Ubuntu 12.04(32 位)下工作,我使用 OpenNI/NITE。 我想找到一只手并将其坐标保存在列表中,对于这一部分,我有以下代码:
标题:
#ifndef HAND_H_
#define HAND_H_
#include <list>
#include<iostream>
#include <stdio.h>
class Hand
{
public:
std::list<double> Xpoints;
std::list<double> Ypoints;
std::list<double> Zpoints;
Hand(int id);
int handID;
void AddPoint(double x, double y, double z);
void ClearList(void);
void ReleaseHand(void);
int GetID(void);
int Size();
};
#endif
CPP:
#include "Hand.h"
Hand::Hand(int id)
{
handID = id;
}
void Hand::AddPoint(double x, double y, double z)
{
("Hand ID: %d: (%f,%f,%f)\n", handID, x, y, z);
if(handID > 0)
{
Xpoints.push_back(x);
Ypoints.push_back(y);
Zpoints.push_back(z);
("Added to Hand ID: %d: (%f,%f,%f)\n", handID, x, y, z);
}
else
{
std::cout << "Hand does not exist anymore - Inconsistency!" << std::endl;
}
}
void Hand::ClearList(void)
{
Xpoints.clear();
Ypoints.clear();
Zpoints.clear();
}
void Hand::ReleaseHand(void)
{
handID = -1; // if (ID==-1) no valid hand
Xpoints.clear();
Ypoints.clear();
Zpoints.clear();
}
int Hand::GetID(void)
{
return handID;
}
int Hand::Size()
{
return Xpoints.size();
}
此处 AddPoints()
被调用:
Hand hand(cxt->nID);
hand.AddPoint(cxt->ptPosition.X, cxt->ptPosition.Y, cxt->ptPosition.Z);
handlist.Add(&hand);
而且效果很好。 稍后,当我从我的 kinect 获得手的新坐标时,我称之为:
Hand tmp = handlist.Get(cxt->nID);
tmp.AddPoint(cxt->ptPosition.X, cxt->ptPosition.Y, cxt->ptPosition.Z);
std::cout << "Hand size " << tmp.Size() << std::endl;
在这里,当它第一次被调用时,第二组坐标被添加到我手中的列表中。但是在那之后列表不能大于大小 2。这意味着不是插入,而是替换最后的点。 (我把它们打印出来了,所以我可以看到坐标)
我也尝试过 push_front
替换前面的坐标,以及 vector 而不是列表,它对 push_back
和 insert
有同样的问题.
我还在使用 VS2010 的 Windows 中尝试了相同的代码,但效果很好。
我完全不知道自己做错了什么。
所以如果有人能帮助我就太好了。 :)
最佳答案
我看到了几个问题。
一个是将指向堆栈变量的指针添加到 handlist。一旦手超出范围,您就会有一个悬空指针。
其次,您的 handlist.Get 正在(大概)通过拷贝返回,因此您添加到其中的任何内容都不会反射(reflect)在 handlist 占用的版本中。即:你可以调用handlist.Get(),加500点,再调用handlist.Get,就是原来的版本。
您的 handlist.Get() 函数也没有返回指针,但是您向 handlist.Add() 传递了一个指针,因此您的界面不清晰。
关于c++ - 列表元素被替换而不是插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14566894/