December 30th, 2019

How do I make a clone of a Windows Runtime vector in C++/CX?

There are still some people maintaining code bases written in C++/CX, even though C++/WinRT is the new hotness. Suppose you have a reference to a Windows Runtime vector in C++/CX, either an IVector<T>^ or an IVector­View<T>^, and you want to clone it so that you can operate on the clone without affecting the original.

You could create a vector and copy the items across:

IVector<Thing^>^ original = GetTheThings();
Vector<Thing^> vec = ref new Vector<Thing^>();
for (auto&& thing : original)
{
  vec->Append(thing);
}

You can make the Vector run the loop by using the constructor overload that takes a pair of iterators.

IVector<Thing^>^ original = GetTheThings();
Vector<Thing^> vec = ref new Vector<Thing^>(begin(original), end(original));

Even more directly, you could slurp the entire collection into a std::vector and then move the std::vector into a new Platform::Collections::Vector.

IVector<Thing^>^ original = GetTheThings();
Vector<Thing^> vec = ref new Vector<Thing^>(to_vector(original));

 

Topics
Code

Author

Raymond has been involved in the evolution of Windows for more than 30 years. In 2003, he began a Web site known as The Old New Thing which has grown in popularity far beyond his wildest imagination, a development which still gives him the heebie-jeebies. The Web site spawned a book, coincidentally also titled The Old New Thing (Addison Wesley 2007). He occasionally appears on the Windows Dev Docs Twitter account to tell stories which convey no useful information.

1 comment

Discussion is closed. Login to edit/delete existing comments.