14

I need to convert a std::array to a std::vector, but I could not find anyway to do it quickly. Here is the sample code:

 std::array<char,10> myData={0,1,2,3,4,5,6,7,8,9};

Now I need to create a vector such as:

std::vector<char> myvector;

and initialize it with the array values.

What is the fastest way to do this?

3
  • Good question, really, but why is the array typeof char and the initializer list uses numbers? Commented Dec 2, 2018 at 16:48
  • 1
    @RYoda I want to array of data which can behold inside a char, so no reason to define the array of int which consumes more memory. Commented Dec 4, 2018 at 16:54
  • 1
    @mans Should probably use int8_t for that. Commented Nov 26, 2019 at 14:37

4 Answers 4

32

You can use the constructor of std::vector taking iterators.

Constructs the container with the contents of the range [first, last).

e.g.

std::array<char,10> myData = {0,1,2,3,4,5,6,7,8,9};
std::vector<char> myvector(myData.begin(), myData.end());
Sign up to request clarification or add additional context in comments.

Comments

7

Just for variety:

std::vector<char> myvector(std::begin(myData), std::end(myData);

Comments

3

I'd use the range constructor of vector - looking like myvector(myData.begin(), myData.end())

for future reference: http://en.cppreference.com/w/cpp/container/vector/vector

Comments

3
std::vector<char> myvector { myData.begin(), myData.end() };

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.