2016-10-02 56 views
-1

我无法将新点添加到当前点矢量的末尾。它正在做的是用我试图添加的新点覆盖现有的矢量,只留下1个元素的矢量。Push_back正在替换当前点而不是向矢量添加新点

这是类定义(h文件):

class person 
{ 
public: 
    person(); 
    ~person(); 

    int ID; 
    std::vector<cv::Point> history; 

    void addposition(cv::Point); 
    void person::drawhistory(cv::Mat*,std::vector<cv::Point>); 
}; 

这是怎么出现在类的.cpp文件中的函数声明:

person::person() 
{ 
} 

person::~person() 
{ 
} 

void person::addposition(cv::Point inpt) { 
    std::cout << "Adding a position ----" << std::endl; 
    std::cout << "Pushing inpt.x: " << inpt.x << std::endl; 
    std::cout << "Pushing inpt.y: " << inpt.y << std::endl; 
    history.push_back(inpt); 
    std::cout << "Current Size: " << history.size() << std::endl; 
    if (history.size()>15) 
    { 
     history.erase(history.begin()); 
    } 
} 

void person::drawhistory(cv::Mat* image, std::vector<cv::Point> hist) { 
    cv::Point pt; 
    for (cv::Point const& pt : hist) 
    { 
     std::cout << "Printing the History" << std::endl; 
     std::cout << "Current Pt.x: " << pt.x << std::endl; 
     std::cout << "Current Pt.y: " << pt.y << std::endl; 
     cv::circle(*image, pt, 5, cv::Scalar(0, 0, 0), -1); 
    } 
} 

这是如何在主函数中调用这两个函数。需要注意的是detectBox被宣布为:

vector<RECT> detectBox

,并正确地存储在帧所需的点,因此即时通讯相当肯定,这是不是问题的原因:

for (RECT const& rect : *detectBox) 
{ 
     std::cout << "Inside the LOOOOOP" << std::endl; 
     //This is simply finding the middle point of the rectangle currently stored in detectBox   
     pt.y = (rect.bottom + rect.top)/2; 
     pt.x = (rect.left + rect.right)/2; 

    person personn; 
    personn.addposition(pt); 
    personn.drawhistory(&img_8bit, personn.history); 

    cv::circle(img_8bit, pt, 3, cv::Scalar(255, 255, 0), -1); 
} 
cv::imshow("8Bit", img_8bit); 

我认为将点推入矢量会很简单,但不知何故它不会将新点添加到矢量的底部。另外请注意,我添加了一个擦除步骤,保存的点数存储为15.

是我的类定义中的函数的问题(我是新来的类),还是它是一个问题从主循环调用函数?

+1

您每次通过循环创建一个新的'person'实例。每个这样的例子都诞生了,获得了一个单一的点,然后死亡。在循环之外声明变量。 –

+0

因为当我打印_history_的当前大小时,它只返回1的大小。我期待矢量最多可以建立15个最近的点。 –

回答

2

这很可能是你想要做的不是什么:

person personn; 
personn.addposition(pt); 
personn.drawhistory(&img_8bit, personn.history); 

presonn是本地的循环体,从而在每次迭代创建一个新的person,添加一个位置并打印该。只需在循环外声明personn即可。

PS:问题的MCVE看起来是这样的:

#include <vector> 
#include <iostream> 
int main() { 
    for (int i=0; i<5; i++) { 
     std::vector<int> vect; 
     vect.push_back(i); 
     std::cout << vect.size() << std::endl; 
    } 
} 

它再现您遇到的问题,它编译和它只有必要的最少的代码来做到这一点。如果你自己创造了自己,你可能自己发现了错误。当然,找到错误的根源并不总是那么容易。调试器可能会帮助找到出错点。

+0

该程序非常大,因此添加所有内容都是不必要的,但现在会尝试为您重新创建问题。 –

+0

@JamesMallett编辑了答案,向您展示了什么是mcve可能看起来像 – user463035818

+0

感谢您的帮助和建议。我将来的问题肯定会做到这一点。 –