这可能是一个基本问题..我有这样的类(class):
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
是一个指向 MyStructure
的迭代器容器中的元素 n
.这是我遇到的问题。我不知道 vector<MyStructure> data
的大小提前(当我构造对象时)。所以我不能简单地分配 *it >> data[i]
.这段代码可以编译,但会因运行时错误而崩溃。我怎样才能解决这个问题?如果可能,解决方案需要高效(也就是说,它应该避免制作太多 MyStructure
对象的拷贝)。
最佳答案
MyStructure temp;
*it >> temp;
data.push_back(std::move(temp));
这避免了制作太多 MyStructure
对象的拷贝。它只制作足够的拷贝。
如果 n
是一个容器,它有一个 size
成员函数,那么首先这样做:
data.reserve(n.size());
关于c++ - 初始化 std::vector 的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19916814/