列表元素被替换而不是插入

list elements get replaced instead of inserted

本文关键字:插入 替换 列表元素      更新时间:2023-10-16

我目前正在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替换前面的坐标,以及向量而不是列表,这对push_backinsert有同样的问题。我也在 Windows 中使用 VS2010 尝试了相同的代码,它工作正常。我完全不知道我做错了什么。

所以如果有人能帮助我,那就太好了。 :)

我看到了几个问题。

一个是将指向堆栈变量的指针添加到手柄列表。 一旦手超出范围,你就有一个悬空的指针。

第二,你的手单。Get 通过副本返回(大概),因此您添加到其中的任何内容都不会反映在手列表占用的版本中。 即:您可以调用handlist。Get(),添加 500 分,然后调用手单。再次获取,它将是原始版本。

您的手单。Get() 函数也没有返回指针,但您正在传递手列表。Add() 一个指针,所以你的界面不清楚。