指针问题 - 查找奇数并将其存储在数组中

问题描述 投票:0回答:1

我得到了这个函数,我添加了这段代码来遍历数组中的数字,然后我有另一个变量来计算奇数的数量,放入第二个数组

int CopySelected(const int array[], int size, int odd_numbers[])
{
    int oddCounter = 0;
    int i;
    for (i = 0; i < size; ++i)
     {
         if (array[i]%2 != 0)
         odd_numbers[++oddCounter] = array[i];
     }
    return oddCounter;
    
}

代码因错误通过,但失败了。 有什么建议吗?

c++ arrays sorting pointers
1个回答
0
投票

看来您正在从有点过时的来源学习 C++。这是一个使用当前 C++ 的示例。

#include <algorithm>
#include <iostream>
#include <vector>
#include <ranges> //C++20 only

bool is_odd(const int value)
{
    return (value % 2) == 1;
}

int main()
{
    // In C++ do NOT use "C" style arrays, use std::vector which is resizable (or std::array fixed size)
    std::vector<int> values{ 1,2,3,4,5,6,7,8,9 };
    std::vector<int> odd_values;

    // range based for loops cannot go out of bound
    // auto& means do NOT copy the values in the vector
    // const promises not to change any of the values 
    // (we're reading them only)
    for (const auto& value : values)
    {
        // use a predicate for readability
        if (is_odd(value))
        {
            odd_values.push_back(value);
        }
    }

    // And output the odd numbers
    for(const auto& value : odd_values)
    {
        std::cout << value << " ";
    }

    std::cout << "\n";
    // Not in C++20 you can also do this
    // no copy of values is needed you just
    // iterate over the odd values only
    for(const auto & value : values | std::views::filter(is_odd))
    {
        std::cout << value << " ";
    }

    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.