• Advertisement
Sign in to follow this  

Equating arrays

This topic is 4150 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

If i have two arrays: int a1[10]; int a2[10]; and a1 is initialized, whats a good way make a2 equal a1. the compiler doesn't let me do a2 = a1 so do i have to do a loop or something. is there a faster way? Thanks.

Share this post


Link to post
Share on other sites
Advertisement
You can use either memcpy or just copy it by hand. (A for loop and copy each element)

edit: PS - Use a vector. [wink]

Share this post


Link to post
Share on other sites
Using the std::library:
std::copy(a1,&a1[sizeof(a1)/sizeof(a1[0])],a2);

Or using boost:


boost::array<int,10> a1;
boost::array<int,10> a2;

a1 = a2;

Share this post


Link to post
Share on other sites
Nitage has the right idea(s), assuming an array is the correct model for your data storage. (Although usually one would just write the middle calculation as pointer arithmetic: 'a1 + sizeof(a1)/sizeof(a1[0])'.) In C++, there's really no reason to use something as primitive as memcpy(). (BTW, std::copy comes from the <algorithm> header.)

But if you can't tell me *why* your arrays are *exactly* 10 elements long, and any other value wouldn't make sense, then I would suggest to you to use std::vector, yes.

Of course, if you're working in C (poor you), then memcpy() is your best bet. I'll let you look that up on your own because I really don't like to encourage people to use C.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement