c++ - 为什么我的向量不支持偶数和奇数
问题描述
我尝试使用数组中的向量将偶数和奇数分开==>所以我创建了一个函数,如果数字是奇数,则返回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 << " ";
}
}
解决方案
正如@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
推荐阅读
- python - 不同的 URL 格式使用 Python 的 requests.get 从相同的 API 返回不同的数据类型
- chrome-web-store - 查看发布到 Chrome 网上应用店的以前版本的扩展程序?
- python - 无法用python为这个程序编写脚本,有人可以推荐任何让它工作的东西吗
- twilio - Twilio SMS statusCallbackUrl 不允许使用 405 方法
- wildcard - 如何使用 RIPGREP 使用通配符进行搜索
- swift - 无法设置用户定义的检查属性 Swift Storyboard
- postgresql - PostgreSQL SELECT 语句中的最大表达式数
- python - 如何更新 RadioItems 选项?
- dynamics-crm - Dynamics CRM 365 的 DocuSign 集成 - 状态更新
- javascript - 将 HTML 表单导出到 Excel CSV 不适用于 Element.append() 方法