我首先寫了這個:(按預期作業)
#include<iostream>
using namespace std;
int main() {
int a[5],cpy[5],ctr = 0;
for (int i = 0 ; i<5 ; i ) {
cout<<"Enter Value for index "<<i<<": ";
cin>>a[i];
}
for (int i = 0 ; i<5 ; i )
if (a[i]%2==0) {
cpy[ctr]=a[i];
ctr ;
}
for (int i = 0 ; i<5 ; i )
if (a[i]%2!=0) {
cpy[ctr]=a[i];
ctr ;
}
for (int i = 0 ; i<5 ; i )
cout<<cpy[i]<<" ";
return 0;
}
想通過改進我的邏輯使其更簡潔/更清晰,這就是我想出的:
#include<iostream>
using namespace std;
int main() {
int a[5],cpy[5],ctr = 0;
for (int i = 0 ; i<5 ; i ) {
cout<<"Enter Value for index "<<i<<": ";
cin>>a[i];
}
for (int i = 0 ; i<5 && a[i]%2==0 ; i ,ctr )
cpy[ctr]=a[i];
for (int i = 0 ; i<5 && a[i]%2!=0 ; i ,ctr )
cpy[ctr]=a[i];
for (int i = 0 ; i<5 ; i )
cout<<cpy[i]<<" ";
return 0;
}
預期結果:
Enter Value for index 0: 1
Enter Value for index 1: 2
Enter Value for index 2: 3
Enter Value for index 3: 4
Enter Value for index 4: 5
2 4 1 3 5
運行第二個版本后我得到了什么:
Enter Value for index 0: 1
Enter Value for index 1: 2
Enter Value for index 2: 3
Enter Value for index 3: 4
Enter Value for index 4: 5
1 0 24 0 0
你能建議我在第二個代碼塊中哪里錯了嗎?第一個塊正常作業。
uj5u.com熱心網友回復:
使用范圍 C 20 和流迭代器使這非常好:
void print(const auto& v)
{
std::ranges::copy(v, std::ostream_iterator<int> { std::cout, ", " });
std::cout << '\n';
}
int main()
{
std::vector<int> v { std::istream_iterator<int> { std::cin }, {} };
print(v);
std::ranges::sort(v);
print(v);
std::ranges::sort(v, std::less<> {}, [](auto x) { return std::pair { x & 1, x }; });
print(v);
return 0;
}
https://godbolt.org/z/fhP51hM7s
uj5u.com熱心網友回復:
這里的問題是你永遠不會進入第一個回圈。僅當滿足條件時計數器才遞增,否則回圈中斷。你不應該實作這樣的條件。
我建議您使用 std::vector 嘗試以下操作:
#include<iostream>
#include<vector>
using namespace std;
int main() {
vector<int> a, cpy;
for (int i = 0 ; i<5 ; i ) {
a.push_back(i 1);
}
for (int i = 0 ; i<5; i ) {
if (a[i]%2 == 0)
cpy.push_back(a.at(i));
}
for (int i = 0 ; i<5 ; i ) {
if (a[i]%2 != 0)
cpy.push_back(a.at(i));
}
for (int i = 0 ; i<5 ; i )
cout<<cpy[i]<<" ";
return 0;
}
它按預期作業,并且以更簡潔的方式作業。
uj5u.com熱心網友回復:
問題在這里:
i < 5 && a[i] % 2 == 0
a陣列中的第一個數字是1,這意味著對于第一次迭代,a[i]將為1,并且a[i] % 2 == 0將為假,因此將中斷回圈。
由于這個原因,第一個回圈從未執行過,第二個回圈只執行一次。
您在結果中看到的那些數字0 24 0 0只是記憶體中的垃圾值,因為實際上只有 1 個數字被寫入cpy陣列。您可以啟動除錯器或簡單地列印出來ctr,它將是1.
uj5u.com熱心網友回復:
我的回答假設只需要在賠率之前對偶數進行分組,并且組內的內部順序無關緊要(我相信它是由 OP 的代碼暗示的)。
在這種情況下,您可以使用std::partition, 和 lambda 函式來分隔偶數和奇數值。
也不要使用原始 C 陣列,最好使用std::vector.
一個完整的例子:
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
std::vector<int> a = { 1,2,3,4,5 };
std::vector<int> cpy = a; // Create a copy. This could be avoided if you prefer
// Partition into evens and odds:
std::partition(cpy.begin(), cpy.end(), [](int n) {return n % 2 == 0; });
// Print the result:
for (int n : cpy) {
std::cout << n << ", ";
}
std::cout << std::endl;
}
可能的輸出:
4, 2, 3, 1, 5,
請注意,偶數總是在賠率之前,但內部每個組的順序并不能保證。我明白這就是你所需要的。
旁注:
最好避免using namespace std- 請參閱此處為什么“使用命名空間 std;” 被認為是不好的做法?.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/514767.html
標籤:C 数组排序
