C++で2つの文字列の内容を交換する方法は何ですか。
C++の標準ライブラリ関数std::swapを使用することで、2つの文字列の内容を交換できます。
以下はサンプルコードです。
#include <iostream>
#include <string>
int main()
{
std::string str1 = "Hello";
std::string str2 = "World";
std::cout << "交换前:" << str1 << " " << str2 << std::endl;
std::swap(str1, str2);
std::cout << "交换后:" << str1 << " " << str2 << std::endl;
return 0;
}
実行結果:
交换前:Hello World
交换后:World Hello
上記の例では、std :: swap関数を使用してstr1とstr2の内容を交換しました。