0

a is set< int> ARRAY, I want to copy it to b. BUT...

int main(){

set<int> a[10];
a[1].insert(99);
a[3].insert(99);
if(a[1]==a[3])cout<<"echo"<<endl;

set<int> b[10];
memcpy(b,a,sizeof(a));
if(b[1]==b[3])cout<<"echo"<<endl;// latch up here, what happen?

return 0;}

Do you know What is computer doing?

1 Answer 1

0

I assume the 'set' class you are using is a std::set? What makes you think that simplying memcpying the raw bytes of a std::set (or array of them, in this case) will work properly? This is highly dependent on the internal structure and implementation of the set class, and trying to do such a thing with anything more complicated than a primitive or array of primitives is almost guaranteed to give unexpected results. Doing this sort of raw byte manipulation when classes are involved is rarely going to be correct.

To do this properly you should iterate over the sets and use their '=' operator to assign them, which knows how to copy the contents properly:

for(int i = 0; i < 10; ++i) {
  b[i] = a[i];
}

Even better you can use std::copy:

std::copy(std::begin(a), std::end(a), std::begin(b));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.