首页 > 解决方案 > 为什么我的向量不支持偶数和奇数

问题描述

我尝试使用数组中的向量将偶数和奇数分开==>所以我创建了一个函数,如果数字是奇数,则返回true是偶数和false,然后我使用if else语句,如果函数返回true,那么它推回向量中的值,如果函数返回 false,则推回另一个向量中的值,最后我打印了向量中的所有元素,但输出不显示任何元素,除非它在奇数向量中显示一个。

#include <iostream>
#include <vector>

using namespace std;

bool sort(int arr[] , int i){
    if(arr[i] %2 == 0){
        return true;
    }
    return false;
}

int main(){
    int n;
    cin >> n;
    int *arr = new int[n];
    for(int i=1 ; i<=n ; i++){
        arr[i-1] = i;
    }
    vector <int> even , odd;
    int i=0 ;
    if(sort(arr , i)){
        even.push_back(arr[i]);
        sort(arr , i+1);
    }else{
        odd.push_back(arr[i]);
        sort(arr,i+1);
    }

    cout << "the even numbers are : " << endl;
    for(auto element:even){
        cout << element << " ";
    }
    cout << endl;
    cout << "the odd numbers are : " << endl;
    for(auto element:odd){
        cout << element << " ";
    }
}

标签: c++

解决方案


正如@TonyDelroy所说,您必须for循环调用sort(arr, i). 第一个循环也应该上升到i <= n而不是i < n.

您的固定工作代码如下(另见std::partition_copy变体):

在线尝试!

#include <iostream>
#include <vector>

using namespace std;

bool sort(int arr[] , int i){
    if(arr[i] %2 == 0){
        return true;
    }
    return false;
}

int main(){
    int n;
    cin >> n;
    int *arr = new int[n];
    for(int i=1 ; i<=n ; i++){
        arr[i-1] = i;
    }
    vector <int> even , odd;

    for (int i = 0; i < n; ++i)
        if (sort(arr, i))
            even.push_back(arr[i]);
        else
            odd.push_back(arr[i]);

    cout << "the even numbers are : " << endl;
    for(auto element:even){
        cout << element << " ";
    }
    cout << endl;
    cout << "the odd numbers are : " << endl;
    for(auto element:odd){
        cout << element << " ";
    }
}

输入:

10

输出:

the even numbers are : 
2 4 6 8 10 
the odd numbers are : 
1 3 5 7 9 

正如@chris所说,您还可以使用std::partition_copy来实现您的算法:

在线尝试!

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

int main() {
    int n = 0;
    std::cin >> n;
    std::vector<int> arr(n), odd, even;
    for (int i = 1; i <= n; ++i)
        arr[i - 1] = i;

    std::partition_copy(arr.cbegin(), arr.cend(),
        std::back_insert_iterator(odd), std::back_insert_iterator(even),
        [](auto const & x){ return (x & 1) == 1; });

    std::cout << "the even numbers are : " << std::endl;
    for (auto element: even)
        std::cout << element << " ";
    std::cout << std::endl << "the odd numbers are : " << std::endl;
    for (auto element: odd)
        std::cout << element << " ";
}

输入:

10

输出:

the even numbers are : 
2 4 6 8 10 
the odd numbers are : 
1 3 5 7 9 

推荐阅读