简体   繁体   中英

Initializing the size of std::vector

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

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

This avoids making too many copies of MyStructure objects. It makes just enough copies.

If n is a container which has a size member function, then do this first:

data.reserve(n.size());

Maybe:

std::deque<int> accumulate;
for(...) accumulate.push_back(...);
// Getting a continuous vector
std::vector result(accumulate.begin(), accumulate.end()):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM