我試圖通過檢查變數 x來找到陣列的磁區,當小于 x 時,它們將在一側或另一側。但我的代碼需要一些更正。這里無法找到錯誤,如果您能幫助我,我將不勝感激。代碼是:-
#include<iostream>
using namespace std;
int partition(int arr[],int n,int x){
for(int i=0;i<n;){
if(arr[i]<x){
i ;
}
else if(arr[i]==x){
int temp=arr[i];
arr[i]=arr[n];
arr[n]=temp;
i--;
}
else if(arr[i]>x){
int temp=arr[i];
for(int j=i;j<n;j ){
arr[j]=arr[j 1];
}
arr[n]=temp;
i--;
}
}
return 0;
}
int main(){
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i ){
cin>>arr[i];
}
int x;
cin>>x;
partition(arr,n,x);
for(int i=0;i<n;i ){
cout<<arr[i]<<"\t";
}
return 0;
}
Input >> array={2,10,15,1,3,15} ,x=10
Expected << {2,1,3,10,15,15}
Output I get << nothing .
uj5u.com熱心網友回復:
代碼沒有給出任何輸出,因為首先,“cin”和“cout”是大寫的,這在語法上是不正確的,其次,變數 j 在回圈陳述句和第二個 else-if 子句中的主體中的大小寫不同在磁區函式中,main() 函式中第一個 for 回圈中的“I”也是如此。解決這個問題,你應該很高興。
uj5u.com熱心網友回復:
首先在 C 中,陣列的大小必須是編譯時常量。例如,請考慮以下示例:
int n = 10;
int arr[n]; //INCORRECT
正確的寫法是:
const int n = 10;
int arr[n]; //CORRECT
同樣,在您的代碼中,
int n;
cin>>n;
int arr[n]; //INCORRECT because n is not a constant expression
其次,在你的代碼中,當你寫:
arr[n] = temp; Undefined behavior
你越界了,所以你有未定義的行為。
解決方案
您可以使用std::stable_partition和std::vector來解決您的問題,如下所示:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
int n;
std::cout <<"Enter n:"<<std::endl;
std::cin >> n;
std::vector<int> arr(n); //create a vector of size n instead of an array
std::cout<<"Enter elements: "<<std::endl;
//iterate and take input from user
for(int &elem: arr){
std::cin >> elem ;
}
int x;
std::cout << "Enter x: "<<std::endl;
std::cin>>x;
//use std::partition
std::stable_partition(arr.begin(), arr.end(), [x](int i){return (i < x);});
std::cout<<"This is the partitioned vector: "<<std::endl;
for(int i=0;i<n;i )
{
std::cout<<arr[i]<<"\t";
}
return 0;
}
輸出
上述程式的輸出如下:
Enter n:
6
Enter elements:
2
10
15
1
3
15
Enter x:
10
This is the partitioned vector:
2 1 3 10 15 15
可以在這里看到。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/395632.html
上一篇:請求文本,然后以特定方式遍歷字母
