首页 > 解决方案 > 在两个数组之间切换特定元素并将切换的元素放置在第一个数组的末尾

问题描述

我正在努力做到这一点,所以如果我输入数字 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++

解决方案


您可以使用更简单的方法在 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]。

希望这会有所帮助。


推荐阅读