c++ - 在两个数组之间切换特定元素并将切换的元素放置在第一个数组的末尾
问题描述
我正在努力做到这一点,所以如果我输入数字 3 ,矩阵将变为 {1,2,4,5,6,7,8,9,10,11,12,0},我不是确定在两个数组之间切换元素的方法是否是最好的方法,我正在尝试使用指针来做
using namespace std;
#include <iomanip>
int main() {
int arr[3][4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, i, j,c;
int* ptr = &arr[0][0];
int zero[3][4] = { 0,0,0,0,0,0,0,0,0,0,0,0 };
int* zptr = &zero [0][0];
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 4; j++)
{
cout << setw(8) << arr[i][j] << ' ';
}
cout << endl;
cout << ' ' << endl;
}
for (i = 0; i < 3; i++) {
if (arr[i][0] = i)
{
break;
}
for (int j = 0; j < 4; j++)
cin >> i;
cout << ptr;
}
return 0;
}
解决方案
您可以使用更简单的方法在 C++ 中使用向量来实现此目的,并通过查找输入元素的索引,考虑以下示例:
int getIndex(vector<int> v, int K) {
auto it = find(v.begin(), v.end(), K);
// calculating the index of K
// note that here i'm supposed the input is valid
int index = it - v.begin();
return index;
}
你可以使用你得到的索引1)在A中追加元素B [index],2)将B [index]分配给A [index]和3)擦除元素A [index]。
希望这会有所帮助。
推荐阅读
- core-data - 这段代码会产生保留周期吗?(核心数据执行)
- ruby - 红宝石中的机架是什么?红宝石中的美洲狮是什么?
- rest - 当当前用户禁止连接点时,我的服务器是否应该为 HTTP OPTIONS 方法返回 200?
- regex - 多个字符的正则表达式匹配
- amazon-s3 - aws s3 cp 将文件下载到匹配文件名的本地
- java - 可选或默认的泛型参数
- javascript - 从 Javascript 中的 HTML 表单获取数据总是产生字符串?
- kotlin - 有没有优雅的方法可以在 kotlin 和箭头中将 List 变成 NonEmptyList?
- reactjs - 反应原生点击突出显示的单词
- performance-testing - JMETER 4. 0 | JMeter 分布式负载测试 | jp@gc - 步进线程组 | 报告