0

This may be an elementary question.. I have class that looks like this:

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. 
        }
    }

}

Note that it is an iterator that points to MyStructure elements in container n. Here's the problem I have. I don't know the size of vector<MyStructure> data in advance (when I construct the object). So I can't just simply assign *it >> data[i]. This code compiles but it will crush with a run time error. How can I fix this? The solution needs to be efficient if possible (that is, it should avoid making too many copies of MyStructure objects).

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 に答える