954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Assigning a dynamic array to a vector

Hi,

This is my first post, this site has been very helpful in the past. I am wondering if it is possible to assign a dynamic array to a vector? If so, how? The following code is not working for me (with Visual Studio .NET 2003):

int *current;
	current = new int[10];

	vector<int> vectorOfInts;	

	for (int i = 0; i < 10; i++)
	{
		vectorOfInts.push_back(i);
	}

	current = vectorOfInts.begin();

	for (int i = 0; i < 10; i++)
	{
		cout << current array, entry: " << i << " is: " << *(current + i);
	}
andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

You cannot use the overloaded operator = to directly assign a vector to an integer array. The = operator is overloaded to allow you to assign one vector to another vector.

This is the protoype :
vector operator=(const vector& c2);

In your case you will probably need to loop through the vector and copy its contents into the array.

stilllearning
Posting Whiz
309 posts since Oct 2007
Reputation Points: 161
Solved Threads: 43
 

See if you can use vector::get_allocator()
I'm not sure if it would work, but try it

Sci@phy
Posting Whiz in Training
279 posts since Sep 2008
Reputation Points: 110
Solved Threads: 43
 

You cannot use the overloaded operator = to directly assign a vector to an integer array. The = operator is overloaded to allow you to assign one vector to another vector.

This is the protoype : vector operator=(const vector& c2);

In your case you will probably need to loop through the vector and copy its contents into the array.

Ah, now I see what you mean about the operator = being overloaded already. I will try to loop through and copy the contents, thanks for your help (I am not seeing how using vector::get_allocator() can help me in this case).

andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

just use the vector constructor that takes 2 iterators as parameters

vector vectorOfInts ( current , current + 10 );

if u're vector is allready constructed u could

vectorOfInts.assign( current, current + 10 );

if u want to append

copy( current, current + 10, back_inserter( vectorOfInts ) );

kux
Junior Poster
119 posts since Jan 2008
Reputation Points: 66
Solved Threads: 11
 

just use the vector constructor that takes 2 iterators as parameters

vector vectorOfInts ( current , current + 10 );

if u're vector is allready constructed u could

vectorOfInts.assign( current, current + 10 );

if u want to append

copy( current, current + 10, back_inserter( vectorOfInts ) );

Hi Kux,

Thanks for your post, I would have done this if I was trying to copy the values in array "current" to the vector; however, I want to do the other way around, copy the values already in a vector into the array "current".

My problem was actually a bit more complex; I wanted to copy into my dynamic int array *current some values from a pointer to a vector of pointers to vectors. But I got to work now, woo-hoo! Thanks everyone.

andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

>however, I want to do the other way around, copy
>the values already in a vector into the array "current".
That's completely opposite from everything else you've said thusfar. Allow me to summarize:

You: "I want to assign a dynamic array to a vector."
Us: "Here's how you do it."
You: "Duh, I know how to do that. What I really want is to assign a vector to a dynamic array. Wow, you aren't very helpful, are you?"

If you mislead people with your questions, how can you expect a decent answer?

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

Hi,

This is my first post, this site has been very helpful in the past. I am wondering if it is possible to assign a dynamic array to a vector? If so, how? The following code is not working for me (with Visual Studio .NET 2003):

int *current;
	current = new int[10];

	vector<int> vectorOfInts;	

	for (int i = 0; i < 10; i++)
	{
		vectorOfInts.push_back(i);
	}

	current = vectorOfInts.begin();

	for (int i = 0; i < 10; i++)
	{
		cout << current array, entry: " << i << " is: " << *(current + i);
	}

hmm is this the best way to do it?

kub365
Junior Poster in Training
89 posts since Nov 2003
Reputation Points: 11
Solved Threads: 1
 

Hi Kux,

Thanks for your post, I would have done this if I was trying to copy the values in array "current" to the vector; however, I want to do the other way around, copy the values already in a vector into the array "current".

My problem was actually a bit more complex; I wanted to copy into my dynamic int array *current some values from a pointer to a vector of pointers to vectors. But I got to work now, woo-hoo! Thanks everyone.

Hi again Kux,

Thanks again for your post, your post correctly answered my initial question, though I later realized (thanks to Narue) that I mis-stated my question (i.e., when I wrote that I wanted to assign an array to a vector, I meant that I wanted to fill in this array's contents with the contents of the vector). I now see that I should have written "assign a vector to an array".

andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

Hi Narue,

First off, thanks for responding to my post, and (indirectly) correcting me on how to use the word "assign" (I now see that I wanted to assign a vector to a dynamic array, not what I originally wrote, a dynamic array to a vector).

So what I was trying to accomplish the entire time (copying the values currently in a vector to a new dynamically allocated int array) had never changed, but as Kux (correct) response was to my (miswritten) question, I stated that his response wouldn't work. Kux hasn't responded back, so I'm guessing my response made things clear enough not to warrant a response, but I could be wrong.

However, I need to disagree with the content and tone of your reply. Firstly, I never said "Duh", that's your (condescending) language. I don't apprecaite putting words into my mouth. I also didn't say "you aren't very helpful, are you", but instead, I said "Thanks for your post, I would have done this...". People make mistakes as they learn...

The whole reason I asked the question was to just to identify how to get the contents of the vector (actually, a pointer to a vector of pointers to vectors) into an array; I felt ok with handling the pointer indirection stuff myself.

>> If you mislead people with your questions, how can you expect a decent answer?

You are certainly right, I can't expect a decent answer to my question if it was (at least partially) ill-posed (by the way, I think the code I posted indicates my reasonable attempt to assign a vector to a dynamic array, when I wrote current = vectorOfInts.begin()).

So all the same, how can you expect people to feel comfortable around this forum, those who are learning, if you feel the need to scold people and put words in their posts? I mean, it's not like this is an isolated response of yours; I've noticed that your words come across as quite condescending in other posts. As I originally said, this was my first post, and what can I say, I'm learning. While I appreciate your insights, frankly, you ought to consider creating a more friendly environment for those not as "learned" as you (and yes, I can see you have a vast knowledge of C++).

It's a shame that someone with such vast knowledge and comprehension of C++ can be so condescending - the quote beneath your username is quite apropos.

andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

>I don't apprecaite putting words into my mouth.
The web is a wonderful place where words you think are perfectly benign can be interpreted as completely different from what you intended. Since I'm not psychic and all of the nuances of face to face communication are lost on a web forum, you'll just have to suffer with me calling it like I see it.

>how can you expect people to feel comfortable around this forum
You assume that making people feel comfortable is a goal of mine. I have three goals on Daniweb: help the moderator team work as efficiently as possible (Narue the Super Mod), enforce the rules (Narue the Moderator), and participate in discussions on topics that interest me (Narue the forum goer). I don't care if you're comfortable, and in fact, a certain measure of discomfort is an excellent way to keep from making mistakes.

>I mean, it's not like this is an isolated response of yours
I don't claim to be nice. I'm amazed when someone decides to lecture me about how I'm a horrible person and should strive to be better, when it's obvious that I know exactly what I am and have no intention of changing.

>you ought to consider creating a more friendly environment for those not as "learned" as you
You assume that I'm only harsh to those not as "learned" as I. Not so. I've blasted all of the C++ gurus on Daniweb at some point. It just happens less often because they're generally better at avoiding me.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 
Not so. I've blasted all of the C++ gurus on Daniweb at some point. It just happens less often because they're generally better at avoiding me.

Wow, you're so cool !!! When I grow up I want to be just like you !!! I just hope I'll be able to call myself "KUX THE GURU BLASTER, NO USE AVOIDING ME".

template <class T>
bool makearray( const vector<T> &myvec, T* &my_new_array, size_t &array_size ) throw()
{
	typedef vector<T>::value_type array_type;
	array_size = myvec.size();

	try{
		my_new_array = new array_type[ array_size ];
	}catch ( bad_alloc& )
	{
		return false;
	}

	try{
		copy ( myvec.begin(), myvec.end(), my_new_array);
	}catch(...)
	{
		delete[] my_new_array;
		return false;
	}
	return true;
}


Anyway, 4 andyT, this is a "generic" way of solving your problem. This function has 3 parameters. First is an input parameter: it takes a vector of any type. Second, is a T* reference as an output parameter. Before the call it must be an uninitialized pointer, after the call it will be a pointer to an array that will contain a copy of your vector. Don't forget to delete[] it after u use it !! Third is an output parameter: after the call, it will hold the number of elements of the new allocated array. You must know this so you know how many elements your array has, so you'll won't cause overflows.
The function returns true if the function succedes and false if not. It is guaranteed to throw no exception.

kux
Junior Poster
119 posts since Jan 2008
Reputation Points: 66
Solved Threads: 11
 

What's a hot thread!..

I don't know why you want to copy vector contents into dynamically allocated array. I think it's not so good idea: you get a new pointer to the heap then have a new trouble with its deallocation in a proper moment. You always can obtain a pointer to &v[0] (it's a valid pointer until the vector size is changed).

But if you need a special function template to copy vector contents into array, better keep it so simple as you can, for example:

template <typename V>
typename V::value_type* makearray(const V& v) {
    V::value_type* p = 0;
    size_t n = v.size();
    if (n) {
        p = new V::value_type[n];
        for (size_t i = 0; i < n; ++i)
            p[i] = v[i];
    }
    return p;
}
...
std::vector<int> v;
... v.push_back(...
int* p = makearray(v);
if (!p) {
   ... the only reason was v.size() == 0;
   ... break the code: no sense to continue...
}
... // You have v.size() in this context,
    // no need in a special parameter...
... do what you want to do...
...
delete [] p;
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 
But if you need a special function template to copy vector contents into array, better keep it so simple as you can, for example:

Yep, ArkM's version is better: it works for any container type. Another problem with my implementation is that I forgot to check if the vector is empty or not. If it's empty the program will crash... :(

kux
Junior Poster
119 posts since Jan 2008
Reputation Points: 66
Solved Threads: 11
 

What's a hot thread!..

I don't know why you want to copy vector contents into dynamically allocated array. I think it's not so good idea: you get a new pointer to the heap then have a new trouble with its deallocation in a proper moment. You always can obtain a pointer to &v[0] (it's a valid pointer until the vector size is changed).

But if you need a special function template to copy vector contents into array, better keep it so simple as you can, for example:

template <typename V>
typename V::value_type* makearray(const V& v) {
    V::value_type* p = 0;
    size_t n = v.size();
    if (n) {
        p = new V::value_type[n];
        for (size_t i = 0; i < n; ++i)
            p[i] = v[i];
    }
    return p;
}
...
std::vector<int> v;
... v.push_back(...
int* p = makearray(v);
if (!p) {
   ... the only reason was v.size() == 0;
   ... break the code: no sense to continue...
}
... // You have v.size() in this context,
    // no need in a special parameter...
... do what you want to do...
...
delete [] p;

Wow, I'm learning a lot from looking at your response ArkM. It's more than I would have conceived; after looking at it, I see the benefits of having such a function (especially if I was assigning lots of vectors to arrays). Thanks for the suggestion (and thanks too, kux, for yours).

To answer your question about copying the contents of a vector into a dynamic array, it actually came up because I'm updating some earlier code written by a guy in C, and I have been trying to make use of the STL library where possible. Eventually, I imagine that the dynamic array will transition into a vector as I progress...

andyT
Newbie Poster
12 posts since Sep 2008
Reputation Points: 11
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You