提问者:小点点

在C++中有没有其他方法来填充数组而不需要向量


所以我有数组A和B,其中两个包含随机数,我需要在C数组中首先写入偶数A和B,然后写入奇数。我制作了这个wtih矢量,但是我想知道是否有其他方法来实现它,比如在Javascript中有。unshift(),。push()等方法

#include<iostream>
#include<vector>
using namespace std;

int main() {
    const int n = 4;
    int A[n];
    int B[n];
    vector<int>C;
    for (int i = 0; i < n; i++)
    {
        A[i] = rand() % 10;
        cout << A[i] << " ";
    }
    cout << endl;
    for (int i = 0; i < n; i++)
    {
        B[i] = rand() % 30;
        cout << B[i] << " ";
    }
    for (int i = 0; i < n; i += 1)
    {
        if (A[i] % 2 == 0)
        {
            C.push_back(A[i]);
        }
        if (B[i] % 2 == 0)
        {
            C.push_back(B[i]);
        }
    }
    for (int i = 0; i < n; i++)
    {
        if (A[i] % 2 != 0)
        {
            C.push_back(A[i]);
        }
        if (B[i] % 2 != 0)
        {
            C.push_back(B[i]);
        }
    }
    cout << endl;
    for (int i = 0; i < C.size(); i++)
        cout << C[i] << " ";
}

共3个答案

匿名用户

我建议首先交错ab:

for (int i = 0; i < n; i += 1)
{
    C.push_back(A[i]);
    C.push_back(B[i]);
}

然后将C划分为偶数和奇数元素:

std::stable_partition(C.begin(), C.end(), [](int i) { return i % 2 == 0; });

匿名用户

vector::push_back是使集合随着向末尾添加内容而增长的最简单方法。

因为A和B的大小是固定的,所以你可以把它们变成基元数组,这就是你所做的。但是对于C,你不知道它会有多长时间,所以一个具有可变大小的集合是合适的。

匿名用户

如果知道编译时需要的大小,可以使用std::array。然后可以使用迭代器进行添加。

#include<vector>
using namespace std;

int main() {
    const int n = 4;
    int A[n];
    int B[n];
    std::array<int, n+n>C;  // <-- here
    auto C_it = C.begin();  // <-- here

    for (int i = 0; i < n; i++)
    {
        A[i] = rand() % 10;
        cout << A[i] << " ";
    }
    cout << endl;
    for (int i = 0; i < n; i++)
    {
        B[i] = rand() % 30;
        cout << B[i] << " ";
    }
    for (int i = 0; i < n; i += 1)
    {
        if (A[i] % 2 == 0)
        {
            *C_it++ = A[i]; // <-- here
        }
        if (B[i] % 2 == 0)
        {
            *C_it++ = B[i];
        }
    }
    for (int i = 0; i < n; i++)
    {
        if (A[i] % 2 != 0)
        {
            *C_it++ = A[i];
        }
        if (B[i] % 2 != 0)
        {
            *C_it++ = B[i];
        }
    }
    cout << endl;
    for (int i = 0; i < C.size(); i++)
        cout << C[i] << " ";
}

或者,如果您想要更安全,您可以保存下一个未写索引,并使用c.at(Last++)=a[i]访问元素,它检查是否超出边界并抛出异常,而不是UB。

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中有|方法来|填充|数组|不需要|向量)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?