简体   繁体   English

C ++-矢量图 <class> 和std :: bad_alloc

[英]C++ - vector <class> and std::bad_alloc

I am working on translating a program from matlab code to C++ where I have to use opencv libs on Linux (gcc version 4.9.2) 我正在将程序从Matlab代码转换为C ++,其中我必须在Linux(gcc版本4.9.2)上使用opencv库

So I am trying to translate this line of matlab code: 所以我正在尝试翻译这行matlab代码:

repeatedMat = repmat(originalMat,[1 1 k]); 

and the last code I wrote is this: 我写的最后一个代码是这样的:

void repeat(cv::Mat img, std::vector <cv::Mat> &output, uint32_t nx, uint32_t ny, uint32_t z)
{
    cv::Mat tmpMat = cv::repeat(img, nx, ny);
    output = std::vector <Mat> (z);

    for (uint32_t i = 0; i < output.size(); i++)
        output.insert(output.end(), tmpMat);
}

The problem is that I always run into std::bad_alloc error 问题是我总是遇到std :: bad_alloc错误

terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc
Aborted

I don't know exactly why but I am thinking about some memory leak.. Is there a better (and working) way to do this ? 我不知道为什么,但是我正在考虑内存泄漏。是否有更好的(可行的)方法来做到这一点?

In C++, the condition of a for loop is evaluated in every iteration, so if you add a new element at the end of the vector, it grows by 1, so in the next iteration the counter i will not reach it. 在C ++中, for循环的条件会在每次迭代中进行评估,因此,如果在向量的末尾添加一个新元素,则它会增加1,因此在下一次迭代中,计数器i不会到达它。 It should be something like: 应该是这样的:

for (uint32_t i = 0; i < z; i++)
    output.insert(output.end(), tmpMat);

But as rahnema1 said in the comments, you don't need to do that. 但是正如rahnema1在评论中所说,您不需要这样做。 You can create a vector with z copies of the same element without copy them: 您可以创建具有相同元素的z副本的向量,而无需复制它们:

output = std::vector <Mat> (z, tmpMat);

Also, because you have labelled your question as "c++11", let me another additional suggestions: return the vector by value, the compiler will avoid the copy. 另外,因为您已将问题标记为“ c ++ 11”,所以让我提出另一个建议:按值返回向量,编译器将避免复制。

std::vector <cv::Mat> repeat(cv::Mat img, uint32_t nx, uint32_t ny, uint32_t z)
{
    return std::vector<cv::Mat>(z, cv::repeat(img, nx, ny));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM