Click here to Skip to main content
15,867,308 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do you convert the std::vector to system::array?

I dared to do

C++
array<int>^ Arr = gcnew array<int>( stdVec.size());

for(int i=0; i < stdVec.size(); i++)
{
  Arr[i] = stdVec[i];
}

There wasn't a compiler error so I dont know if this is actually ok or not. My program crashes at this line though so I'm hoping the reason is the conversion and not something else.

Many thanks as always
Posted
Updated 27-Mar-13 12:01pm
v2
Comments
[no name] 27-Mar-13 18:05pm    
"My program crashes" is not helpful information. Why does it crash? What is the actual error message? What is the exception?
Sergey Alexandrovich Kryukov 27-Mar-13 18:11pm    
Exactly. I answered, anyway... :-)
—SA
lostandconfused1234 27-Mar-13 18:26pm    
Additional information: Index was outside the bounds of the array.

both are declared as int...
lostandconfused1234 27-Mar-13 18:30pm    
also I changed my code to that above, so the array size is dependent on the vector size
lostandconfused1234 27-Mar-13 18:33pm    
ah fml found the issue.

1 solution

First of all, don't hard-code your 10, this makes the code completely unsupportable. Ever heard of constants? Do you understand that it could be a variable?

As to the code, it looks correct, but who knows what is stdVec, where it is declared? You should not ask anything about some unknown part of the code. Believe or not, but because of late spring and massive snow melting, my access to your hard drive is somewhat limited. If you declare stdVec correctly as an instance of std::vector of int, your code will work correctly. Please see:
http://www.cplusplus.com/reference/vector/vector/[^].

Should be something like
C#
#include <vector>
using namespace std;

//...

vector<int> stdVec;
// only name the object in a humanly manner, is some semantically significant way
// same goes about "Arr" and "i"... :-)


Just for some fun, please see this CodeProject article: Arrays in C++/CLI[^].

—SA
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900