Archived

This topic is now archived and is closed to further replies.

Copying memory from vector?

This topic is 5378 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Say I have a vector of integers: std::vector<int>integerList Is it possible to somehow access the integers as an array and copy them using something like memcpy? Or is this simply not possible? Thanks edit by ze: changed left angle bracket to the appropriate HTML entity. [edited by - zealouselixir on March 25, 2003 12:41:44 PM]

Share this post


Link to post
Share on other sites
you can although it's not standard (yet)

vector<int> myInts;

myInts.push_back(9);
myInts.push_back(5);
myInts.push_back(2);
myInts.push_back(1);
myInts.push_back(5);

&myInts[0] will be the pointer to the beginning of the contiguous memory. Check your implementation works like that.

[edited by - petewood on March 25, 2003 3:09:05 PM]

Share this post


Link to post
Share on other sites
As the above link says .. it IS standard, in the sense of the current, expanded standard ... meaning the ratified standard plus the current addition and corrections. And here''s another reason it is standard ... the published purpose of vector is to provide a container which uses contiguous memory and therefore has the same benifits as arrays ... if you look at the performance rules for vector you will see that it is almost impossible for any implementation to meet those rules and not use contiguous memory (because they require constant time access, which mean all final address must be mathmatically computable, or looked up, without iteration). To my knowldege these has never been any implementation of any std::vector class ANYWHERE, which does not use contiguous memory ... and the reason is simple ... in the eyes of the use (programmer) any other implementation would not be a vector.

Share this post


Link to post
Share on other sites
On the same token, an iterator object for some vector implementations is simply a pointer. But if you're going to assume the memory is contiguous, might as well skip the iterator interface as well

[edited by - Zipster on March 25, 2003 7:39:30 PM]

Share this post


Link to post
Share on other sites

  
#include <vector>

#include <algorithm>

using namespace std;

...

vector<int> v1(20); // 20 element vector

generate( v1.begin(), v1.end(), rand ); // fill with random ints


int array[20];
copy( v1.begin(), v1.end(), array ); // copy into an array




[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]

Share this post


Link to post
Share on other sites