简体   繁体   中英

using push_back to put a vector<double> into a vector<vector<double>>

I have a std::vector<vector<double>> I want to fill in one function. I need to store some 3 dimensional coordinates for some calculations later in my program.

My Question is if I do this:

//in classdefinition
std::vector<std::vector<double>> data;

    myFunc()
    {
        std::vector<double> temp;
        temp.push_back(1);
        temp.push_back(2);
        temp.push_back(3);
        data.push_back(temp);

        temp.clear();
        //new data
        temp.push_back(2);
        temp.push_back(3);
        temp.push_back(4);
        data.push_back(temp);
    }

will the clearing and refilling of temp influence the values in data?

I already found this http://www.cplusplus.com/reference/vector/vector/push_back/ but since the explanation reads "The content of val is copied (or moved) to the new element." I don't know what to think. To me this sounds like a contradiction.

I think it would not make much sense if the variables are passed as a reference since they can, like in my case, only be valid in a limited scope. Am I right with my assumption?

If data is of type std::vector<std::vector<double>> then you're fine: a value copy of temp will be taken; so you're free to do as you please with temp after you've used it as the push_back argument.

If, however, you've messed about with the vector's allocator then you might need to take more care.

Using emplacement (see emplace_back ) can obviate the unnecessary deep copy:

// First row of data
{
    std::vector<double> temp = {1, 2, 3}; /*ain't C++11 brilliant?*/
    data.emplace_back(std::move(temp)); /*do not use temp after this line - 
                                use scope blocks so you're not tempted*/
}

You could do that as a one-liner although in reality I suspect you want to populate temp with a bit more care. So I've kept the two lines separate.

As you can see in doc there are two overloaded versions of push_back function

void push_back (const value_type& val);
void push_back (value_type&& val);

The first takes const reference to val and copies it into vector. The second one uses rvalue reference (see move sematics for more information) and moves val into vector leaving source vector empty. Neither of them stores reference to temporary object inside vector.

First version will call when you pass, for example, local variable.

std::vector<std::vector<double>> v;
std::vector<double> lv = {1, 3, 7};
v.push_back(lv);

the second one - when you pass temporary variable or explicitly move variable

v.push_back(std::vector<double>({0, 17, 42}));
v.push_back(std::move(lv));

“复制”是指push_back(temp)和“(或者移动)”是指push_back(std :: move(temp))

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