我目前遇到一个小问题,我想在std :: string中交换内容.
#include <iostream>
#include <string>
void swap(char* t1, char* t2); // function parameter is wrong syntax
int main(){
std::string message = "ABC";
swap(message[0], message[1]); // parameter probably wrong here
return 0;
}
void swap(char * t1, char * t2){
return;
}
Run Code Online (Sandbox Code Playgroud)
目标:我希望对索引0和1中的内容进行简单交换,以便在交换之后,消息"ABC"变为"BAC".正如你所看到的,我试着这样做,就像我使用普通数组一样,但似乎这种逻辑不能用于字符串.我明白,如果我切换到
char a[] = "ABC";
Run Code Online (Sandbox Code Playgroud)
它会工作,但我想尝试使用字符串类.
类型message[n]是char.所以你的交换函数的签名应该是
swap(char& a, char& b);
Run Code Online (Sandbox Code Playgroud)
但你应该使用std::swap.
#include <iostream>
#include <string>
#include <utility>
int main(){
std::string message = "ABC";
std::swap(message[0], message[1]);
std::cout << message << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |