Search code examples
c++managed

C++ vector with managed objects


Hello I need to have vector (or some other data structure, which is similar) filled with managed objects.

Usually I can write:

std::vector<Object> vect;

But I cannot use:

std::vector<Object^> vect;

Can somebody explain, how to change declaration or advice other structure instead of vector. Thanks.


Solution

  • Use .NET generic List class: http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx

    List enumeration sample from the same WEB page, as requested by user1237747's comment:

    #include "stdafx.h"
    using namespace System;
    using namespace System::Collections::Generic;
    
    int main(array<System::String ^> ^args)
    {
        List<String^>^ dinosaurs = gcnew List<String^>();
    
        dinosaurs->Add("Tyrannosaurus");
        dinosaurs->Add("Amargasaurus");
    
        for each(String^ dinosaur in dinosaurs )
        {
            Console::WriteLine(dinosaur);
        }
    
        return 0;
    }
    

    Replace String^ with the type you need. You can also access List elements by index using [] operator.

    Generally, avoid mixing managed and unmanaged types, if this is not absolutely necessary.