0

这可能是一个基本问题。我的课程看起来像这样:

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是一个指向MyStructurecontainer 中元素的迭代器n。这是我遇到的问题。我不知道vector<MyStructure> data提前的大小(当我构造对象时)。所以我不能简单地分配*it >> data[i]. 此代码可以编译,但会因运行时错误而崩溃。我怎样才能解决这个问题?如果可能,解决方案需要高效(也就是说,它应该避免制作太多的MyStructure对象副本)。

4

2 回答 2

4
MyStructure temp;
*it >> temp;
data.push_back(std::move(temp));

这样可以避免制作过多的MyStructure对象副本。它只制作足够的副本。

如果n是具有size成员函数的容器,则首先执行以下操作:

data.reserve(n.size());
于 2013-11-11T22:04:40.793 回答
1

也许:

std::deque<int> accumulate;
for(...) accumulate.push_back(...);
// Getting a continuous vector
std::vector result(accumulate.begin(), accumulate.end()):
于 2013-11-11T22:14:58.773 回答