Convert std::vector to array - c++

I have a library which expects a array and fills it. I would like to use a std::vector instead of using an array. So instead of
int array[256];
object->getArray(array);
I would like to do:
std::vector<int> array;
object->getArray(array);
But I can't find a way to do it. Is there any chance to use std::vector for this?
Thanks for reading!
EDIT:
I want to place an update to this problem:
I was playing around with C++11 and found a better approach. The new solution is to use the function std::vector.data() to get the pointer to the first element.
So we can do the following:
std::vector<int> theVec;
object->getArray(theVec.data()); //theVec.data() will pass the pointer to the first element
If we want to use a vector with a fixed amount of elements we better use the new datatype std::array instead (btw, for this reason the variable name "array", which was used in the question above should not be used anymore!!).
std::array<int, 10> arr; //an array of 10 integer elements
arr.assign(1); //set value '1' for every element
object->getArray(arr.data());
Both code variants will work properly in Visual C++ 2010. Remember: this is C++11 Code so you will need a compiler which supports the features!
The answer below is still valid if you do not use C++11!

Yes:
std::vector<int> array(256); // resize the buffer to 256 ints
object->getArray(&array[0]); // pass address of that buffer
Elements in a vector are guaranteed to be contiguous, like an array.

Related

Creating and filling array dynamically

I have an array which is to be filled using an object like this -
const std::map<Id, std::vector<Data>> *const DataSets[]=
{
&object.data1,
&object.data2,
&object.data3,
&object.data4
};
Condition here is, If object.data1.size() == 0 I dont want to push it into array. in that case I want to fill my array like this -
const std::map<Id, std::vector<Data>> *const DataSets[]=
{
&object.data2,
&object.data3,
&object.data4
};
UPDATE
I am using std::vector instead of array now and trying to initialize vector in same as array -
const std::vector<std::map<Id, std::vector<Data>>> *const DataSets
{
&object.data1,
&object.data2,
&object.data3,
&object.data4
};
I am getting error: E0146 too many initializer values. Can't I initialize my vector in this way? If not can anyone please suggest how to do that?
Thanks in advance!
You don't do that.
Respectively you don't use C style plain arrays if you want to do anything dynamic. You just wrap it in yet another std::vector because that supports dynamic sizes.
[...] since my further logic depends upon this arraya and the code is long
back implemented...thatswhy not using vector
Thats not a good reason for not using a vector. If you ever need a c-array you can still use std::vector::data() in combination with std::vector::size(). There is (almost) no good reason to prefer a c-array to a std::vector, even if you need c-arrays in some places.

How to create variable name with integer appended to the end?

I want to create a for loop that will fill a bunch of arrays with data in c++. Now to save space and in the future once more arrays are added which they will, I have the for loop. Each array for demonstration purposes is called Array# (# being a number) The point of the for loop would be to set a constant with maximum arrays, then cycle through each array filling by appending i to the end of the Array name.
For example in pseudo code:
for (i = 1; i < numberofarrays; i++)
{ fill (Array & i) with ("Array" & i & "-default.txt")}
It is impossible to generate Variable Names by any type of code.
(Meaning it is impossible to generate dynamic variable names on Runtime or on Compiletime)
The best solution possible would be a array of arrays:
int Arrays[][];
Calling Arrays[0] would give you the first array.
If you want to determine the number of arrays during Runtime you need to use pointers!
That would look like that:
(int[])* Arrays = new (int[])[numberofarrays];
Accessing the arrays in the array would work the same!
An alternative would be using the container vector from std.
The code would the look like this:
#include<vector>
// More includes
// Optional
using namespace std;
// Somewhere in your code
vector<vector<int>> Arrays;
You still would acces the elements by using your standard array method (Arrays[15][78] e.g.)
You don't really need the name. You can use an std::vector of arrays. This will not work out of the box, see Correct way to work with vector of arrays
Another approach would be to have an std::map of arrays. You could have the name as the key, if that is what you really want. You will still have to use the same workaround as before to have an array as a value. See Character Array as a value in C++ map for example.

How to make a number returned from a function be used for defining no of elements in an array?

I am using Opencv/c++.
I get the number of frames in a video using the function
int noOfFrames = cvGetCaptureProperty( capture, CV_CAP_PROP_FRAME_COUNT );
I have also declared an array int Entropy[noOfFrames];. But as the variable noOfFrames is non-const, it gives an error.
I even used const_cast for this but still it gives an error. I want the length of the array to be equal to the no of frames of the video.
How can I do it ???
You can't declare a static array with a dynamic size. You need a dynamic array:
int* Entropy = new Entropy[noOfFrames];
// use here, same as array
delete[] Entropy;
But using a vector is just easier:
std::vector<int> Entropy(noOfFrames);
// use here, same as array and more
// no need to clean up, std::vector<int> cleans itself up
In C++, you cannot do that because the size of a c-style array should be a compile-time constant1.
Anyway, you have a superior alternative : use std::vector
std::vector<int> Entropy(noOfFrames);
Even if you have compile-time constant, I would not suggest you to use int arr[size] which is c-style array. Instead I would suggest you to use std::array<int,size> arr; which is again far superior solution.

counting elements stored in an array

I really need some help... I detail my problem, I need an array of a certain type, but I don't know its length before having retrieving values from other arrays, using for structures. In fact, I don't want to spend time passing again the several loops, and i wonder the best way to do this. Should I use a stack and a counter, and after filling it, instanciate and fill the array ?
RelAttr *tab;
//need to initialize it but how
/*several for loops retrieving values*/
tab[i] = value;
/*end for loops*/
Obviously this code is incomplete, but it is how stuff is done. And i know i can't do the affectation without having specified the array length before...
Thanks for your help
Just use a std::vector.
std::vector<RelAttr> vec;
vec.push_back(a);
vec.push_back(b);
...
It manages its own growth transparently. Every time it grows, all the items are copied, but the amortized cost of this is O(1).
The storage is also guaranteed to be contiguous, so if you really need a raw C-style array, then you can simply do this:
const RelAttr *p = &vec[0];
However, you should really only do this if you have a legacy C API that you need to satisfy.
As this is C++, suggest using a std::vector (std::vector<RelAttr>) as the number of objects is not required to be known beforehand. You can use std::vector::push_back() to add new elements as required.
The easiest way (assuming nothing exceptionally performance critical) is to use a std::vector to assemble the values and (if needed) convert the vertor to an array. Something like;
std::vector<RelAttr> vec;
...
vec.push_back(value);
...
and if you want to convert it to an array afterwards;
RelAttr *tab = new RelAttr[vec.size()];
copy( vec.begin(), vec.end(), a);
If you don't know length at compiling time you can use
function malloc, operator new, vector or another type of container

PUSH an array C++?

How would I dynamically add a value (push) to an array? I could do this in AS3, but I can't find a function for it in C++.
You can't if it's a statically defined array like so:
int array[10];
Its size is fixed. However, if you use a container such as std::vector you'd use:
std::vector::push_back()
It is not possible to 'push' in a statically allocated classic C-style array and it would not be a good idea to implement your own 'method' to dynamically reallocate an array, this has been done for you in the STL, you can use vector:
#include <vector>
// ...
std::vector<int> vect;
vect.push_back(1);
vect.size(); // --> 1
vect.push_back(2);
vect.size(); // --> 2
// ...
Use a std::vector. You cannot push into a C style array e.g. int[].
Assuming you don't mean a std::vector<>, where you obviously would use std::vector<>::push_back(), but an actual array, then you need to know
Is there at least one unused slot at the end of the array?
Yes? then put the value at the first unused slot. No? Allocate memory for a new array that is at least the size of the previous plus any amount of additional slots that you want, copy the old values over there and add the new value.
The above of course implies that you know where in the available memory the last used slot resides.
This is what std::vector<> is for, you know.