convert array to vector

Converting to a vector works in main but when I call changeAR, it does not (dataVector size == 0, should be 3). What am I doing wrong? Thanks!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
using namespace std;

 void changeAR(double* dataArray)
{
	vector<double> dataVector(dataArray, dataArray + sizeof dataArray / sizeof dataArray[0]);	
	cout << dataVector.size()<<endl;	
}

void main()
{
	double dataArray[] = { 3.79e-11, 6.90474, 319.08 };
	vector<double> dataVector(dataArray, dataArray + sizeof dataArray / sizeof dataArray[0]);
	cout << dataVector.size() << endl;

        //this doesn't work
	//changeAR(dataArray);
}
Last edited on
does this work...
vector<double> x = dataArray;

A standard array doesn't carry its own size (like a vector would), so no size information would get passed via the argument list. After all, this function might have to cope with lots of different-size arrays.

You could try the following if you want. Not sure you really need a function to do this, though.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <vector>
using namespace std;

vector<double> changeAR( double* dataArray, int size )
{
	return vector<double>( dataArray, dataArray + size );
}

int main()                  // <===== int main, please!
{
	double dataArray[] = { 3.79e-11, 6.90474, 319.08 };
	vector<double> dataVector(dataArray, dataArray + sizeof dataArray / sizeof dataArray[0]);
	cout << dataVector.size() << endl;

	vector<double> anotherDataVector = changeAR(dataArray, sizeof dataArray / sizeof dataArray[0] );   // <==== pass the size as a parameter
	cout << anotherDataVector.size() << endl;
	for ( auto e : anotherDataVector ) cout << e << " ";
}
Last edited on
In C++, main returns an int. Not void. Always always always.

Inside the function, dataArray is a pointer. Not an array. A pointer. In main, it's known to be an array, but in the function changeAR, it's a pointer. A single pointer. Of size 8 (or possibly 4). So,

sizeof dataArray is 8 (or possibly 4).
sizeof dataArray[0] is 8 (or possibly 4).
sizeof dataArray / sizeof dataArray[0] is 8/8 , which is 1.

So you're not copying any of the array.



Start debugging. Here's an example:
1
2
3
4
5
6
void changeAR(double* dataArray)
{
    cout << "sizeof dataArray = " << sizeof dataArray << ", sizeof dataArray[0] = " << sizeof dataArray[0] << '\n';
	vector<double> dataVector(dataArray, dataArray + sizeof dataArray / sizeof dataArray[0]);	
	cout << dataVector.size()<<endl;	
}


Last edited on
In main the compiler knows that dataArray is an array with 3 elems.
In changeAR dataArray has decayed to a simple pointer.
When using pointer or old C arrays you always need to pass the number of elems.
Thanks guys, that would have taken me a long time figure out!
Good catch on the void main, what a rookie mistake.
Last edited on
Topic archived. No new replies allowed.