![](/img/trans.png)
[英]'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.