c++一个数组删除偶数组成新的数组
时间: 2024-06-13 19:07:02 浏览: 13
以下是使用C++删除偶数组成新数组的例子:
```c++
#include <iostream>
#include <vector>
using namespace std;
vector<int> removeEven(vector<int>& arr) {
vector<int> res;
for (int i = 0; i < arr.size(); i++) {
if (arr[i] % 2 != 0) {
res.push_back(arr[i]);
}
}
return res;
}
int main() {
vector<int> arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
vector<int> res = removeEven(arr);
for (int i = 0; i < res.size(); i++) {
cout << res[i] << " ";
}
return 0;}
```
相关问题
c++一个数组取出偶数删除组成新的数组
以下是C++中一个数组取出偶数删除组成新的数组的代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int nums[] = {1, 2, 3, 4, 5, 6};
int numsLen = sizeof(nums) / sizeof(int);
int evenCount = 0;
for (int i = 0; i < numsLen; i++) {
if (nums[i] % 2 == 0) {
evenCount++;
}
}
int evenNums[evenCount];
int index = 0;
for (int i = 0; i < numsLen; i++) {
if (nums[i] % 2 == 0) {
evenNums[index] = nums[i];
index++;
}
}
cout << "原数组为:";
for (int i = 0; i < numsLen; i++) {
cout << nums[i] << "\t"; }
cout << endl;
cout << "新数组为:";
for (int i = 0; i < evenCount; i++) {
cout << evenNums[i] << "\t";
}
cout << endl;
return 0;}
```
运行结果为:
```
原数组为:1 2 3 4 5 6
新数组为:2 4 6
```
c++一个数组取出偶数删除删除偶数组成新的数组
以下是C++中一个数组取出偶数删除删除偶数组成新的数组的代码实现:
```c++
#include <iostream>
using namespace std;
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int evenArr[n], oddArr[n];
int evenCount = 0, oddCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
evenArr[evenCount] = arr[i];
evenCount++;
} else {
oddArr[oddCount] = arr[i];
oddCount++;
}
}
int newEvenArr[evenCount];
for (int i = 0; i < evenCount; i++) {
newEvenArr[i] = evenArr[i];
}
cout << "New even array: ";
for (int i = 0; i < evenCount; i++) {
cout << newEvenArr[i] << " ";
}
cout << endl;
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)