简体   繁体   中英

what happened in this auto loop?

vector<int> nums = {1, 2, 3};
vector<vector<int>> subsets = {{}};
for(int i=0; i<3; i++)
    for(auto subset : subsets)
    {
        subset.push_back(nums[i]);
        subsets.push_back(subset);
    }

The content of subsets , after running, turns out to be:

[[] [1] [2] [2] [3] [3] [3] [3]]

However, I was expecting:

[[] [1] [2] [1 2] [3] [1 3] [2 3] [1 2 3]]

It seems like only the first element, which is an empty vector<int> , being considered.

Could you please tell me what exactly happened in terms of memory allocation?

PS: I also changed subsets.push_back(subset) into subsets.push_back(vector<int>(subset)) , but it still gives the same incorrect result.

There are a few things that will not work as expected:

for(auto subset : subsets) Says "Give me a modifiable copy of the element." Change auto to auto& to receive a modifiable reference .

Range-based for-loops are intended to be used to view a constant range of elements . If you modify the range the iterators will be invalidated. Use a standard for loop instead.

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