如何通过函数 C++ 传递字符串

how to pass a string through a function c++

本文关键字:字符串 C++ 何通过 函数      更新时间:2023-10-16

我只是在学习c++编程。在我的家庭作业中,我需要比较用户通过提示给出的三个字符串。我知道对于直接修改某些值而不是返回值的函数,我需要使用指针。我也知道字符串的行为已经像指针一样。这是我到目前为止的代码,但我不知道我错在哪里:

#include"std_lib_facilities.h"
void switching (string x, string y){
string flag;
if (x>y){flag=y;
y=x;
x=flag;
}
}
int main(){
string  s1, s2, s3;
cout<<"introduce three words: ";
cin>>s1>>s2>>s3;
switching(s1,s2);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
switching(s2,s3);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
switching(s1,s2);
cout<<s1<<" "<<s2<<" "<<s3;
cout<<endl;
return 0;
}

您的函数按值(副本)接收字符串,而不是通过引用(或指针)接收字符串,因此它实际上无法执行您尝试执行的交换。 通过引用接收参数,方法是将原型更改为:

void switching (string& x, string& y){

作为记录,虽然string将指针包装到数组char但它们的行为类似于值,而不是指针;如果您按值接收它们,它们将分配一个新的内存块并将字符串的完整内容复制到其中。这就是为什么如果可能的话,你想要引用语义;否则,您正在制作大量不必要的副本。您可能会想到 C 样式字符串文字和char数组,它们确实作为指向其第一个字符的指针传递,但这不适用于真正的 C++std::strings。

你也可以使用<utility>中的std::swap来避免显式的临时flag对象(如果你不在 C++11 上,<algorithm>,但你现在真的应该在 C++11 上;写 C++11 之前的C++在这一点上只是不必要的受虐狂):

void switching (string& x, string& y){
if (x>y) std::swap(x, y);
}