Alexey
Alexey

Reputation: 5978

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

Upvotes: 0

Views: 118

Answers (2)

user2249683
user2249683

Reputation:

Maybe:

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

Upvotes: 1

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

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());

Upvotes: 4

Related Questions