2016-12-02 65 views
-5

我正在嘗試在C++中編寫一個函數,用它的值來排序整數。例如,如果A = 5,B = 2和c = 3,那麼它會命令他們B,C,一個嘗試按值排序整數

這是代碼,我迄今爲止:

#include "stdafx.h" 
#include <iostream> 

using namespace std; 

void sortThreeIns(int a, int b, int c); 

int main() 
{ 
int a = 3; 
int b = 4; 
int c = 1; 

sortThreeIns(a, b, c) 
{ 
    if (a > b) 
    { 
     int temp = a; 
     a = b; 
     b = temp; 
    } 
    if(a > c) 
    { 
     int temp = a; 
     a = c; 
     c = temp; 
    } 
    if (b > c) 
    { 
     int temp = b; 
     b = c; 
     c = temp; 
    } 
    return 0; 
} 


return 0; 
} 

這使返回箱6語法錯誤,如「預期的一個;」和「語法錯誤:如果」但我不知道爲什麼? 有什麼幫助嗎?

+3

哇,不,回到本書,這是無效的C++。 – DeiDei

+1

你不能在另一個函數中放置一個函數定義。 – user463035818

+1

C++中不允許嵌套函數。 'sortThreeIns'必須在'main'函數之外定義,並且像另一個函數一樣調用。請[找一本好初學者的書或教程閱讀](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。 –

回答

3

本地函數定義在C++中是非法的。

當前sortThreeIns定義main()。所以編譯器發出錯誤。

通過編寫整個功能修復此問題main()以上。此外,由於您已將其標記爲void,因此您不應該爲return一個值。

您還需要原型改爲void sortThreeIns(int& a, int& b, int c&);(即由refererence傳遞參數),所以在功能所做的更改將反映在調用程序中的變量。

最後,考慮使用std::swap來交換兩個元素,而不是自己編碼。

+0

謝謝,我對使用C++非常陌生,所以我忘記了該函數需要在main之外定義,然後在main之內調用一次! 你知道我在哪裏可以閱讀有關交換? –

+0

參見http://en.cppreference.com/w/cpp/algorithm/swap –

0

如果你不使用STL的禁止,你不這樣做,作爲一個學術活動,你可以使用std::vectorstd::sort

std::vector<int> toSort {3, 4, 1}; 
std::sort(toSort.begin(), toSort.end()); 
// toSort now contains 1, 3, 4 

在線例子在這裏:http://melpon.org/wandbox/permlink/NL6CyCSPhz6v5hgm