2012-05-26 25 views
0

我想根據用戶輸入調用函數。我無法弄清楚我做錯了什麼。我不斷收到這個錯誤根據用戶輸入排序或合併

error: no matching function for call to 'sort(std::vector<int, std::allocator<int> >&)' 

有人可以告訴我我做錯了什麼。請徹底解釋任何建議,因爲我是C++的新手。這裏是我的代碼:

#include <iterator> 
#include <algorithm> 
#include <vector> 
#include <fstream> 
#include <iostream> 
#include <string> 

std::ifstream in(""); 
std::ofstream out("outputfile.txt"); 
std::vector<int> numbers; 
std::string sortType = ""; 
std::string file = ""; 

int main() 
{ 
    std::cout << "Which type of sort would you like to perform(sort or mergesort)?\n"; 
    std::cin >> sortType; 

    std::cout << "Which file would you like to sort?\n"; 
    std::cin >> file; 

    //Check if file exists 
    if(!in) 
    { 
    std::cout << std::endl << "The File is corrupt or does not exist! "; 
    return 1; 
    } 

    // Read all the ints from in: 
    copy(std::istream_iterator<int>(in), std::istream_iterator<int>(), 
      std::back_inserter(numbers)); 

    //check if the file has values 
    if(numbers.empty()) 
    { 
     std::cout << std::endl << "The file provided is empty!"; 
     return 1; 
    } else 
    { 
     if(file == "sort") 
     { 
      sort(numbers); 
     }else 
     { 
      mergeSort(); 
     } 
    } 
} 

void sort(std::vector<int>) 
{ 

    // Sort the vector: 
    sort(numbers.begin(), numbers.end()); 

    unique(numbers.begin(), numbers.end()); 

    // Print the vector with tab separators: 
    copy(numbers.begin(), numbers.end(), 
      std::ostream_iterator<int>(std::cout, "\t")); 
    std::cout << std::endl; 

    // Write the vector to a text file 
    copy(numbers.begin(), numbers.end(), 
      std::ostream_iterator<int>(out, "\t")); 
    std::cout << std::endl; 
} 

void mergeSort() 
{ 
     //mergesort code.. 
} 

回答

2

您需要聲明sort功能,然後再調用它。在main之上移動其定義,或在main之前放置void sort(std::vector<int>);

mergeSort也是如此。

你也應該完全限定的通話sort(numbers.begin(), numbers.end());std::sort(numbers.begin(), numbers.end());,與同爲copyunique。如果你不這樣做,那麼出於技術上的原因,稱爲「ADL」,如果你願意,你可以查找它,那麼只有在你調用它的參數(迭代器)是命名空間std中的類時纔會調用該調用。無論它們是否具體取決於具體實現,因此該調用在某些編譯器上不起作用。

+0

這麼簡單,我幾乎尷尬......感謝提示!肯定會做出這些改變。 – Jmh2013

1

我同意@steve在main()之前聲明sort函數。

我認爲這裏的問題是,你打電話sort()功能與參數std::vector但在函數的定義你剛纔寫的接收參數的類型,你也應該寫一些名稱的變量。例如。

void sort(std::vector<int> <variable_name>) { //definition }

還有一件事我要指出的是,正如你所聲明的載體number全球那麼就不需要調用等等sort(number),因爲功能會自動找到全局定義矢量number。所以基本上如果你想全局定義矢量number那麼函數sort()應該是無參數的。

你也使用範圍std::無處不在,而不是你可以添加一行#include年代後右 -

using namespace std;

我希望它的作品!