Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

c++ - Why is this working? I cannot understand the logic of this swapping

int main() {
    // Complete the program
    string a,b;
    getline(cin,a);
    getline(cin,b);
    cout<<a.size()<<" ";
    cout<<b.size();
    string c=a+b;
    cout<<endl<<c;

    swap(a[0],b[0]);
    cout<<endl<<a<<" "<<b;
    return 0;
}
void swap(string s1,string s2){
    string temp=s1;
    s1=s2;
    s2=temp;
}

Well the target is to swap the first element of both strings, but I created a general function for that and even got it right. But, unexpectedly, I didn't use pass by reference or pointer! Even then, the changes are permanent when I try to output a and b in the end!

Logically it shouldn't work but it is working. Is it something to do with the strings?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is almost certainly due to the fact that, somewhere in code that you have not shown us, you have this line (or something very similar):

using namespace std;

With this line included, then that very namespace std defines a function as follows:

void swap(_Ty& _Left, _Ty& _Right);

Where the _Ty template is replaced with char in your swap(a[0],b[0]); call.

Add a simple cout << "My Swap" << endl; line to your swap function, and you'll see it's not being called.

Highly recommended reading: Why is "using namespace std;" considered bad practice?.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...