对数组的第一个和最后一个元素进行C ++迭代

时间:2016-11-23 16:09:11

标签: c++ arrays

假设我有这个数组:

int oldv[10] = {16, 12, 24, 96, 45, 22, 18, 63, 47, 56};

和另一个像

int newv[8]; 

我希望从old的交替端填充新内容,直到满足某个条件,这样我才能拥有:

newv = [16, 56, 12, 47, 24, 63 ...]

假设我想从旧版本中提取新的3个数字(即:16,56,12)。 我已尝试使用以下for循环,但当然还不够......

for(int i = 0; i < 3; i++) 
    newv[i] = oldv[i*(sizeof(oldv)-1)];

任何帮助?

2 个答案:

答案 0 :(得分:-1)

int _old[10] = {16, 12, 24, 96, 45, 22, 18, 63, 47, 56};
int _new[8];

const int old_size = sizeof(_old)/sizeof(int);
const int new_size = sizeof(_new)/sizeof(int);

for (int i = 0; i < new_size; ++i)
{
    if (i % 2)
        _new[i] = _old[old_size - i / 2 - 1];
    else
        _new[i] = _old[i / 2];

    std::cout << _new[i] << " ";
}

std::cout << std::endl;

返回16 56 12 47 24 63 96 18

See it live

答案 1 :(得分:-2)

享受。

#include <algorithm>
#include <iostream>
#include <iterator>

using namespace std;

int main(int, char**)
{
    int oldv[] = { 16, 12, 24, 96, 45, 22, 18, 63, 47, 56 };
    int newv[8];
    size_t numbers_i_want = 3;

    size_t oldv_b = 0;
    size_t oldv_e = sizeof oldv / sizeof *oldv;
    size_t newv_e = sizeof newv / sizeof *newv;

    for(size_t i = 0;
        i != min(numbers_i_want, newv_e) && oldv_b != oldv_e;
        ++i)
    {
        newv[i] = (i % 2) ? oldv[--oldv_e] : oldv[oldv_b++];
    }

    copy(newv, newv + min(numbers_i_want, newv_e),
        ostream_iterator<decltype(*newv)>(cout, " "));
    return 0;
}