Skip to main content
gamedev.net
🔒 Locked

Vector with array

Started by Drunken_Monkey 3 replies 550+ views
Original Post
Drunken_Monkey
Drunken_Monkey

#include <vector>
#include <iostream>

using namespace std;

int main()
{
	vector<float[2]> t;

	float* j[2];

	j[0] = new float;
	j[1] = new float;

	*j[0] = 2;
	*j[1] = 1;

	t.push_back(j); //Error

	return 0;
}


This brings up an error saying "'push_back' : cannot convert parameter 1 from 'float *' to 'const float (&)[2]'" So the compiler doesn't recognize j as an array... Is it even possible to use the vector with arrays? Any help will be appreciated.
Ezbez
Ezbez
IIRC, you have to explicitly cast to const. You can use const_cast<> for this. Google it if you want more information.
Enigma
Enigma
Arrays in C++ do not have the same properties as other types. In particular you cannot assign arrays to each other, as you implicity try to do when you try to push an array onto a vector. The simplest solution is to use Boost.Array instead:

#include <vector>#include <iostream>#include <boost/array.hpp>using namespace std;using boost::array;int main(){	vector< array< float *, 2 > > t;	array< float *, 2 > j;	j[0] = new float;	j[1] = new float;	*j[0] = 2;	*j[1] = 1;	t.push_back(j); //Error	return 0;}

Σnigma
Zahlman
Zahlman
Quote:
Original post by Ezbez
IIRC, you have to explicitly cast to const. You can use const_cast<> for this. Google it if you want more information.


Incorrect. Const correctness *looks* like an issue here, but the real issue is that arrays aren't first-class types in C++. And anyway, you never have to explicitly cast *to* const, and casting *away* const is almost always an extremely bad idea.

Enigma has it right. If you really want to do everything yourself/the hard way, you can wrap the array in your own struct:

class FloatPair {  float f[2];  float& operator[](const size_t& s) { return f[s]; }  const float& operator[](const size_t& s) const { return f[s]; }};vector<FloatPair> t;


However, you should also note:

- There is absolutely no reason to invoke dynamic memory allocation in your program as written. You're also not cleaning up after yourself.
- You made an array of float*, and tried to assign it to an array of float. Even if you *could* assign arrays to each other, how the hell were you expecting that to work?
tendifo
tendifo
This should work. You might consider a smart pointer instead of a raw pointer because cleaning them up is always a pain.

// create itvector<float*> bigarray;float *smallarray1 = new float[2];float *smallarray2 = new float[2];bigarray.push_back(smallarray1);bigarray.push_back(smallarray2);// then clean it upfor (int i = 0; i < (int)bigarray.size(); i += 1){    if (bigarray.at(i) != NULL)    {        delete[] bigarray.at(i);    }}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.