Namespaces
Variants
Views
Actions

Talk:cpp/iterator/move iterator

From cppreference.com

In the example where are the strings moved to? QuentinUK (talk) 12:12, 17 March 2016 (PDT)

Look at http://en.cppreference.com/w/cpp/algorithm/accumulate
it uses init + *first the addition is explained in
http://en.cppreference.com/w/cpp/string/basic_string/operator%2B
by addition no 7 where it says addition is by std::move(rhs.insert(0, lhs)), where rhs is *first. So the accumulation is done by a series of inserts into the strings which are moved to new strings. Each insertion requires new memory allocation.

With regular interators:-
operator&+&
& constructor
append
&& constructor
Delete
&& operator=
Delete thisisan

With move iterators:-
operator&+&&
insert
&& constructor
&& operator=
Delete thisisan

Or reserve the memory
std::string s;
s.reserve(std::accumulate(cbegin(v), cend(v), size_t{}, [](size_t len, const std::string& s)
{
return len + s.size();
}));
std::string concat = std::accumulate(v.cbegin(), v.cend(), std::move(s), [](std::string& a, const std::string& b)
{
a.append(b);
return std::move(a);
});
Or simply
for(auto& b:v) s.append(b);
QuentinUK (talk) 09:36, 21 March 2016 (PDT)



[edit] Illegal code example?

Isn't the code example illegal? Specifically, the use of the string objects that have been moved from here:

   for (auto& s : v)
       std::cout << '"' << s << "\" ";

Should we include a warning?

--77.105.197.115 05:22, 10 February 2019 (PST)

it is a valid use of a moved-from std::string. --Cubbi (talk) 05:49, 10 February 2019 (PST)