vector of vtkDataArray

I want to make a vector of vtkDataArray where each array may be a different type.

I know I can use something like std::vector<vtkDataArray *> data_arrays;
and I can do something like

vtkSmartPointer<vtkDoubleArray> test  = vtkSmartPointer<vtkDoubleArray> ::New();
 // add values to test


Is there a smarter way to do this? will the smart pointer be manage properly or will it need to be deleted later?

You should rather use std::vector<vtkSmartPointer>> v;
and then set your vector:
forall i:
v[i] = vtkSmartPointer ::New();
or you can use
push_back as you showed.

This way the pointers will be deallocated when the vector goes out of scope.


Thank you. I think that I am having a hard time with is how to do it generically?

I want to return a specific type of vtkDataArray as a function of some input type


std::vector<vtkSmartPointer> v;
std::vector<std::string> vars = {"float", "double", "int"};

for (int i = 0; i < vars.size(); ++i) {
  if ( == "float") {
    v.push_back(vtkSmartPointer<vtkFloatArray> ::New());

I see. In that case I don’t have a better solution than just adding the pointers to vktDataArray. You have to make sure the vtkSmartPointer<…> don’t go out of scope before your vector,
otherwise your pointers stored in vector elements will become invalid.

I figured out a solution that worked for me.

I can get the typed array via vtkAOSDataArrayTemplate

vtkDataArray * gettypedarray(FieldDataType_e VarType)
    case TecplotFloat:      return vtkAOSDataArrayTemplate<float>::New();
    case TecplotDouble:     return vtkAOSDataArrayTemplate<double>::New();
    case TecplotLongInt:    return vtkAOSDataArrayTemplate<long>::New();
    case TecplotShortInt:   return vtkAOSDataArrayTemplate<short>::New();
    case TecplotByte:       return vtkAOSDataArrayTemplate<char>::New();
    case TecplotBit:        return vtkAOSDataArrayTemplate<char>::New();
      assert(!"Not a valid VarType!");
std::vector<vtkDataArray *>  pt_data_arrays;
vtkDataArray * data;
for (CZ = 0; CZ < NumZones; CZ++) {
  data = gettypedarray(VarType[CV]);
  for (I = 0; I < NumPts; ++I) {
    data->SetComponent(I, 0, VDataBase[CZ * NumVars + CV][I]);

And after I write the file with the data it gets deleted.

for (int k = 0; k < pt_data_arrays.size(); ++k )

The following should work with vtkSmartPointer:

std::vector<vtkSmartPointer<vtkDataArray>> vec;

auto arr = vtkSmartPointer<vtkFloatArray>::New();
// or 
vtkNew<vtkFloatArray> arr;

/* do stuff with arr */

// or vec.push_back(std::move(arr)); if you're done with arr and want
// to avoid touching the reference count unnecessarily. 

It’s better to use smart pointers in the vector so that you don’t have to worry about the lifetimes of raw vtkDataArray* pointers. The smart pointers have optimized move operations so you won’t have to worry about expensive ref count updates when the vector dynamically resizes.