# How to initialize all elements of Vector?

**URL:** <https://community.haxe.org/t/how-to-initialize-all-elements-of-vector/1623>\
**Category:** Haxe\
**Tags:** std\
**Created:** [March 25, 2019, 3:14pm UTC](https://community.haxe.org/t/how-to-initialize-all-elements-of-vector/1623 "2019-03-25T15:14:25Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![flashultra](https://community.haxe.org/user_avatar/community.haxe.org/flashultra/32/82_2.png) [@flashultra](https://community.haxe.org/u/flashultra)\
**Post date:** [March 25, 2019, 3:14pm UTC](https://community.haxe.org/t/how-to-initialize-all-elements-of-vector/1623/1 "2019-03-25T15:14:25Z")

</div>

On Array I can use comprehension or just to init with

```haxe
     var testArray : Array<Int> = [0x4f727068, 0x65616e42, 0x65686f6c];

```

How can achieve same with Vector ? I saw `fromArrayCopy` and `fromData`, but both require to have already set variables with Array or VectorData . Any other way ?

---

<div class="post-metadata">

**Author:** ![ebishton](https://community.haxe.org/user_avatar/community.haxe.org/ebishton/32/15_2.png) [@ebishton](https://community.haxe.org/u/ebishton)\
**Post date:** [March 27, 2019, 4:27am UTC](https://community.haxe.org/t/how-to-initialize-all-elements-of-vector/1623/2 "2019-03-27T04:27:35Z")

</div>

`var myVector = Vector.fromArrayCopy([0,1,2]);`  
`var anotherOne = Vector.fromArrrayCopy([for (i in 0...3) i]);`

The downside is that the array literal is converted to an array before Vector gets hold of it, so it’s a tiny bit inefficient. However, the objects of the array aren’t duplicated, only the pointers.

---

<div class="post-metadata">

**Author:** ![kevinresol](https://community.haxe.org/user_avatar/community.haxe.org/kevinresol/32/272_2.png) [@kevinresol](https://community.haxe.org/u/kevinresol)\
**Post date:** [March 28, 2019, 12:51pm UTC](https://community.haxe.org/t/how-to-initialize-all-elements-of-vector/1623/3 "2019-03-28T12:51:33Z")

</div>

You can use a macro for that: [http://try-haxe.mrcdk.com/#CC1ae](http://try-haxe.mrcdk.com/#CC1ae)

`Macro.hx`:

```haxe
import haxe.macro.Expr;

class Macro {
  public static macro function initVector(expr:Array<Expr>) {
    return macro {
      var vec = new haxe.ds.Vector($v{expr.length});
      $b{[for(i in 0...expr.length) macro vec.set($v{i}, ${expr[i]})]}
      vec;
    }
  }
}

```

and use with:

```haxe
var vec = Macro.initVector(1, 2, 4, 5, 6);
trace($type(vec));

```
