[英]Initializing the size of std::vector
这可能是一个基本问题。我有一个看起来像这样的课:
class Foo {
private:
vector<MyStructure> data;
public:
void read(const cv::FileNode& node) {
// read data from file
cv::FileNode n = node["MyStructure"];
cv::FileNodeIterator it = n.begin(), it_end = n.end();
for (int i = 0; it != it_end; ++it, ++i) {
*it >> data[i]; // there's a problem here.
}
}
}
请注意, it
是一个指向容器n
MyStructure
元素的迭代器。 这是我的问题。 我事先不知道vector<MyStructure> data
的大小(在构造对象时)。 因此,我不能仅仅分配*it >> data[i]
。 该代码可以编译,但是会因运行时错误而崩溃。 我怎样才能解决这个问题? 如果可能,该解决方案需要高效(也就是说,应避免制作太多MyStructure
对象副本)。
MyStructure temp;
*it >> temp;
data.push_back(std::move(temp));
这样可以避免制作太多MyStructure
对象的副本。 它只制作足够的副本。
如果n
是具有size
成员函数的容器,请首先执行以下操作:
data.reserve(n.size());
也许:
std::deque<int> accumulate;
for(...) accumulate.push_back(...);
// Getting a continuous vector
std::vector result(accumulate.begin(), accumulate.end()):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.