C++:反转数组中的字符串.在两个不同的数组之间交换字符串
C++: Reverse Strings within an array. Swap strings between two different arrays
我已经为这段代码编写了主干。我只需要对如何完成这些功能有一点了解。我认为CCD_ 1将用于交换同一数组中的两个字符串。我错了吗?
如有任何见解/建议,我们将不胜感激。
#include <string>
using std::string;
#include <iostream>
#include <cassert>
using namespace std;
void swap(string & a, string & b); // swaps two strings.
void reverse_arr(string a1[], int n1); // reverse an array of strings.
void swap_arr(string a1[], int n1, string a2[], int n2); // swaps two arrays of strings.
int main(){
string futurama[] = { “fry”, “bender”, “leela”,
“professor farnsworth”, “amy”,
“doctor zoidberg”, “hermes”, “zapp brannigan”,
“kif”, “mom” };
for (int i=0;i<10;i++)
cout << futurama[i] << endl;
swap(futurama[0],futurama[1]);
cout << “After swap(futurama[0],futurama[1]);” << endl;
for (int i=0;i<10;i++)
cout << futurama[i] << endl;
reverse_arr(futurama,10);
cout << “After reverse_arr(futurama,10);” << endl;
for (int i=0;i<10;i++)
cout << futurama[i] << endl;
// declare another array of strings and then
// swap_arr(string a1[], int n1, string a2[], int n2);
char w;
cout << “Enter q to exit.” << endl;
cin >> w;
return 0;
}
void swap(string & a, string & b){
// swaps two strings.
a.swap(b);
}
void reverse_arr(string a1[], int n1) {
// Reverse an array of strings.
}
void swap_arr(string a1[], int n1, string a2[], int n2) {
// swaps two arrays of strings.
}
std::string::swap
函数肯定会交换数组中的两个字符串。。。它执行与CCD_ 3完全相同的功能。也就是说,由于std::string
对象实际上是通过指针管理动态分配的字符串,所以STL版本的swap
实际上不会交换内存块。因此,用于交换实际数组的函数必须在数组中递增,并为每个元素调用swap
。例如:
void swap_arr(string a1[], int n1, string a2[], int n2)
{
for (int i=0; i < min(n1, n2); i++)
{
swap(a1[i], a2[i]);
}
}
对于reverse_arr
函数,您可以做一些非常类似的事情,但只需穿过一半数组(比枢轴位置少一个槽,可以是一个元素,也可以是两个元素之间),而不是整个数组,否则您将把所有东西都交换回原来的位置。
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组