【问题标题】:Push_back is replacing current point instead of adding a new one to the vectorPush_back 正在替换当前点,而不是在向量中添加新点
【发布时间】:2016-10-02 15:21:52
【问题描述】:

我无法将新点附加到当前点向量的末尾。它目前正在做的是用我要添加的新点覆盖现有向量,使向量只有 1 个元素。

这是类定义(.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&lt;RECT&gt; 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。

是我的类定义中的函数有问题(我是类新手),还是我从主循环调用函数的方式有问题?

【问题讨论】:

  • 每次循环都会创建一个person 的新实例。每个这样的实例都会出生,添加一个点,然后死亡。在循环外声明变量。
  • 因为当我打印 history 的当前大小时,它只返回 1 的大小。我期望向量可以建立到最近的 15 个点.

标签: c++ opencv vector point push-back


【解决方案1】:

这很可能不是您想要做的:

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;
    }
}

它重现了您遇到的问题,它可以编译并且它只有最少的代码。如果您自己创建了它,您可能已经自己发现了错误。当然,找到错误的根源并不总是那么容易。调试器可能有助于找到出错的地方。

【讨论】:

  • 程序很大,所以不需要添加所有内容,不过现在会尝试为您重新创建问题。
  • @JamesMallett 编辑了答案以向您展示 mcve 的外观
  • 感谢您的帮助和建议。在我以后的问题中肯定会这样做。
  • 如果人们费心创建minimal reproducible example 80% 的问题不会在这里创建
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多