[英]'std::bad_alloc' or even wrong vector size when using iterator on vector
[英]std::bad_alloc when I forgot to increment the iterator
关于以下代码,我有两个问题。 首先,我最初忘记增加循环,因此在运行代码时得到了std::bad_alloc
。 调试后,我不太明白为什么错误会导致该错误。
我的第二个问题是,是否存在比矢量更有效的方法来存储pcl::PointXYZ
类型的对象? 我可以避免复制它们吗?
#include <unordered_set>
#include <random>
#include <algorithm>
#include <vector>
// Sample without replacement over a range using Bob Floyd's algorithm
std::unordered_set<int> sampleWithoutReplacement(int sampleSize, int rangeUpperBound)
{
std::unordered_set<int> sample;
std::default_random_engine generator;
for(int d = rangeUpperBound - sampleSize; d < rangeUpperBound; d++)
{
int t = std::uniform_int_distribution<>(0, d)(generator);
if (sample.find(t) == sample.end() )
sample.insert(t);
else
sample.insert(d);
}
return sample;
}
unsigned maxIterations {100};
while(maxIterations--)
{
std::unordered_set<int> inliers;
std::unordered_set<int> sampleIndices = sampleWithoutReplacement(sampleSize, cloudSize);
std::vector<pcl::PointXYZ> samplePoints {};
for (auto it { sampleIndices.begin() }; it != sampleIndices.end(); ++it)
{
samplePoints.push_back(cloud->points.at(*it));
}
// some other code that uses samplePoints.
}
关于第一个问题,您可以查看cppreference并查看分配失败时会抛出std :: bad_alloc。 从本质上讲,您通过连续推送到向量已耗尽了内存。
至于总的内存开销,您在现代系统上不会真正看到明显的区别。 如果我们是技术人员,并且您知道要存储多少个元素的确切大小,则数组在内存上的效率会更高。 如果您担心查找元素要花费多长时间,则std :: map比std :: vector快(std :: map的O(logn)和std :: vector的O(n))。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.