c++ - 如何将数组的每个n个元素组合成一个元素

标签 c++ arrays

我有一个 int 数组 a[intPART+1],其元素为 0 和 1。 我想通过 union 数组的每个 n 个元素将这个数组的大小减小到 b[rightSIZE+1],其中

int rightSIZE=    -1              if (intPART+1)/n=0
                  intPART         if n=1
                   0              if (intPART+1)/n=1
                 (intPART+1)/n    if (intPART+1)modn=0
                 (intPART+1)/n-1  if (intPART+1)modn!=0

( 我为 rightSIZE 写了这些条件,我认为它们应该适用于任何 (intPART+1) 和 n )

n can be any number that we want

For example, if we have k = intPART+1 = 8 and if array a=[1,1,1,1,1,0,1,0,0]
     for n=1 we'll have b=[1,1,1,1,1,0,1,0,0]
     for n=2 we'll have b=[1,11,11,01,00]
     for n=3 we'll have b=[111,110,100]
     for n=4 we'll have b=[1,1111,0100]
   for n=200 we'll have b=[111110100] and so on

不幸的是,我真的无法想象这个任务是如何完成的,而且这个任务是我其他任务的一部分,所以我附上了我想要添加这个解决方案的代码的最后一部分(这是一个问题现在对我来说)。希望你能帮助我

我在用C++写

#include <iostream>
#include <math.h>       /* log2(dec) and fmod()*/ 
using namespace std;
int main()
{
int dec=500;//let be
//Decimal to binary
int intPART = log2(dec);
cout << "Int part of log2 (" << dec << ") is " << intPART << endl;
int dec1 = dec;
int *a=new int[intPART+1];
for (int i = 0; i<=intPART; i++)
{
    a[i] = dec1 % 2;
    dec1 = dec1 / 2;
}
cout <<dec<<" in a binary system: ";
for (int i = intPART; i >= 0; i--)
{
    cout << a[i];
}
    int n=2^16;//let be
    int rightSIZE;
    if ((intPART+1)/n==0)       rightSIZE=-1;
    if (n==1)                   rightSIZE=intPART;
    if ((intPART+1)/n==1)       rightSIZE=0;
    if (fmod((intPART+1),n)==0) rightSIZE=(intPART+1)/n;
    if (fmod((intPART+1),n)!=0) rightSIZE=(intPART+1)/n-1;
    int *b=new int[rightSIZE+1];
    //what to do next? I don't know:(

}

最佳答案

据我了解,您想要这样的东西:

template <std::size_t K, std::size_t N>
std::array<int, (N + K - 1) / K>
combine(const std::array<int, N>& a)
{
    std::array<int, (N + K - 1) / K> res{};

    for (std::size_t i = 0; i != N; ++i) {
        res[(N + K - 1) / K - 1 - i / K] += a[N - 1 - i] * pow(10, i % K);
    }
    return res;
}

Demo

关于c++ - 如何将数组的每个n个元素组合成一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58160206/

相关文章:

c++ - C++如果在创建指向堆的指针后不调用 'delete'运算符怎么办?

c++ - 动态 Spirit 解析器取决于标志位

arrays - Swift Vapor 对对象数组的错误解码

arrays - 如何在SAS中创建与另一个数组具有相同维度的数组

c++ - 在 C++ 中检测视频是否没有音频,最好使用 Qt Phonon

c++ - 是否有正确处理 Unicode 的 STL 字符串类?

c++ - 我如何在 GTK 中获得键盘和鼠标输入?

javascript - 我的函数应该将数组分割成更小的数组并将它们放回原始数组,这有什么问题吗?

javascript - 在 Javascript 中删除项目

c - 使用数组作为哈希表