2012-05-26 23 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;

我希望它的作品!