473,409 Members | 2,004 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,409 software developers and data experts.

std::vector to C array

MrPickle
100 100+
Is this the correct way to convert a std::vector to a C array or is there a function that returns the vector as an array?

Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector;
  2. //Fill MyVector
  3.  
  4. int a[MyVector.size()];
  5. for(int i = 0; i < MyVector.size(); i++)
  6.      a[i] = MyVector[i];
  7.  
Oct 27 '08 #1
8 18448
JosAH
11,448 Expert 8TB
Bookmark this site and no, there is no such function.
What you did is basically corrrect.

kind regards,

Jos
Oct 27 '08 #2
boxfish
469 Expert 256MB
Almost, but a static array can't have a variable size. The number of elements in a must be a literal. You should use a dynamic array for this if you don't know how many items are in MyVector:
Expand|Select|Wrap|Line Numbers
  1. int *a = new int[MyVector.size()];
  2. // ...
  3. delete[] a;
  4.  
Hope this helps.
Oct 27 '08 #3
MrPickle
100 100+
What's the difference between my way and your way?
Oct 27 '08 #4
Laharl
849 Expert 512MB
An array declared with the int arr[size] syntax must have a constant size, as the compiler must know how much stack space to allocate. If you want to declare an array of variable length (say, the user inputs it), you have to use the new operator, as the provided code did. The site you were linked to earlier contains a very good tutorial for it under its Documentation link.
Oct 27 '08 #5
MrPickle
100 100+
Okay, thanks.

Would this be any better (if it's right)
Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector;
  2. //Fill Vector
  3.  
  4. int *MyArray;
  5. memcpy(MyArray, &(MyVector[0]), sizeof(MyVector[0]));
[EDIT]
Looking at the site that was linked, is this also correct:
Expand|Select|Wrap|Line Numbers
  1. int *MyArray = MyVector.get_allocator().allocate(MyVector.size());
Oct 27 '08 #6
boxfish
469 Expert 256MB
Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector; 
  2. //Fill Vector 
  3.  
  4. int *MyArray; 
  5. memcpy(MyArray, &(MyVector[0]), sizeof(MyVector[0]));
This is not right, because you have not allocated space for MyArray to copy MyVector into. You are also not copying the whole vector because you are only copying a block the size of the first element. You would have to do it like this:
Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector;
  2. //Fill Vector.
  3. int *MyArray = new int[MyVector.size()];
  4. memcpy(MyArray, &(MyVector[0]), sizeof(MyVector[0]) * MyVector.size());
  5. // Other stuff.
  6. delete[] MyArray;
Or totally the C way:
Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector;
  2. //Fill Vector.
  3. int *MyArray = malloc(sizeof(MyVector[0]) * MyVector.size());
  4. memcpy(MyArray, &(MyVector[0]), sizeof(MyVector[0]) * MyVector.size());
  5. // Other stuff.
  6. free(MyArray);
But I don't think it's an improvement, because you are using the memcpy function from the C language in your C++ program.
As for the way with get_allocator, I don't know how it works, but I have a feeling that it won't.
Why not just stick with
Expand|Select|Wrap|Line Numbers
  1. std::vector<int> MyVector;
  2. //Fill Vector.
  3. int *MyArray = new int[MyVector.size()];
  4. for (int i = 0; i < MyVector.size(); i++)
  5.     MyArray[i] = MyVector[i];
  6. // Other stuff.
  7. delete[] MyArray;
Hope I got all this right and that it's helpful.
Good luck.
Oct 28 '08 #7
MrPickle
100 100+
I wanted to find an alternative way rather than having to loop through and assign each value.

I think I have found a way
Expand|Select|Wrap|Line Numbers
  1. int *MyArray = new int[MyVector.size()];
  2. std::copy(MyVector.begin(), MyVector.end(), MyArray);
Oct 28 '08 #8
Banfa
9,065 Expert Mod 8TB
One of the things that a vector guarantees is that it uses exactly the same memory layout as an array (one of the things that causes inserting/deleting anywhere but the end of the array to be inefficient).

One of the results of this guarantee is that (assuming the vector has 1 or more entries)

&MyVector[0]

Is a pointer to the array of data in the vector in the same way that given

int MyArray[10];

MyArray or &MyArray[0]

is a pointer to the data in the array.

My understanding is that this is guaranteed by the design requirements of the vector template, that is no matter whose implementation you use this should be true if they have written the vector in a compliant manor.

What I can not say is if relying on this is considered good practice.

Additionally it doesn't work in more than 1 dimension, taht is a vector or vectors does not have the same memory layout as a 2 dimensional array.
Oct 28 '08 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: enzo | last post by:
hi all, i don't understand what's wrong: 1) std::vector<double> p(10); doesn't compile:
2
by: Dylan | last post by:
what is the best way of initializing a static std::vector data member with some values? (currently I just push_back some values in the constructor if the size == 0) thanks
17
by: Michael Hopkins | last post by:
Hi all I want to create a std::vector that goes from 1 to n instead of 0 to n-1. The only change this will have is in loops and when the vector returns positions of elements etc. I am calling...
8
by: Ross A. Finlayson | last post by:
I'm trying to write some C code, but I want to use C++'s std::vector. Indeed, if the code is compiled as C++, I want the container to actually be std::vector, in this case of a collection of value...
6
by: slyi | last post by:
Is it ok to assume that the following assertion is valid for all implementations of std::vector?: std::vector<T> v(10); T* p = &v; for (size_t n=0; n < v.size(); n++) assert( p+n == &v ); ...
32
by: zl2k | last post by:
hi, c++ user Suppose I constructed a large array and put it in the std::vector in a function and now I want to return it back to where the function is called. I can do like this: ...
4
by: Bobrick | last post by:
Hi. I'm in the process of making a GUI for a function someone else wrote, and i've come across a type i'm unfamiliar with, namely "std::vector<unsigned char>". I need to get the contents of this...
6
by: Bobrick | last post by:
Hi. Thanks to everyone who replied to my last post, it turns out it wasn't the line where I was trying to treat the variable in question as an array which was the problem, but the line above. ...
3
by: mast2as | last post by:
sorry i am too sure how to write a more explicit subject but this code doesn't compile for the type string and I am not sure why (and I am not sure either how to describe the problem but by looking...
3
by: DevNull | last post by:
I have a program where we load a mapfile, comprised of a .csv with numbers which represent object types at a given position. Each position is in the map is called a Cell, a cell contains only a...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.