使用相同的向量和两个索引来反转向量的值

时间:2019-06-20 22:13:30

标签: c++ arrays

给出一个数字N<30)和一个VEC元素的向量N(包含整数值),将向量的内容求反并报告使用具有两个索引的相同向量


我不知道如何使用给定的要求实现代码。我尝试了以下方法:

for (int i = N - 1; i >= 0; i--) {
    for (int j = 0; j < N; j++) {
        VEC[i] = VEC[j];
    }
    cout << VEC[i] << "\t";
}

但是没有用。

我只能使用iostream库。


作为参考,您可以看到相同的内容,但使用的另一个向量具有:(1)1个索引,(2)2个索引:

#include <iostream>
using namespace std;

void usingAnotherVecWith2Ind(int [], int [], int);
void usingAnotherVecWith1Ind(int [], int [], int);

int main() {
    int N = 0;

    cout << "Enter N: ";
    cin >> N;

    if (N < 30) {
        int VEC[N] = {0}, VEC2[N] = {0};

        for (int i = 0; i < N; i++) {
            cout << "Enter value " << i << ": ";
            cin >> VEC[i];
        }

        usingAnotherVecWith2Ind(VEC, VEC2, N);

        usingAnotherVecWith1Ind(VEC, VEC2, N);
    }

    return 0;
}

void usingAnotherVecWith2Ind(int VEC[], int VEC2[], int N) {
    cout << endl << "The reverse vector using another vector with 2 indices is:" << endl;
    for (int i = N - 1; i >= 0; i--) {
        for (int j = 0; j < N; j++) {
            VEC2[j] = VEC[i];
        }
        cout << VEC2[i] << "\t";
    }
}

void usingAnotherVecWith1Ind(int VEC[], int VEC2[], int N) {
    cout << endl << "The reverse vector using another vector with 1 index is:" << endl;
    for (int i = N - 1; i >= 0; i--) {
        VEC2[i] = VEC[i];
        cout << VEC2[i] << "\t";
    }
}

示例:

Example

编辑。。我无法使用std::reverse

1 个答案:

答案 0 :(得分:0)

感谢评论中的帮助,我得以实现以下目标:

void usingSameVecWith2Ind(int VEC[], int N) {   
    cout << endl << "The reverse vector using the same vector with 2 indices is:" << endl;
    for (int i = N - 1; i >= 0; i--) {
        for (int j = 0; j < N; j++) {
            swap(VEC[i], VEC[j]);
        }
        cout << VEC[i] << "\t";
    }
}
void swap(int ind1, int ind2) {
    int aux;
    aux = ind1;
    ind1 = ind2;
    ind2 = aux;
}
相关问题