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..
}
4

2 回答 2

2

您需要sort在调用它之前声明该函数。把它的定义移到上面main,或者放在void sort(std::vector<int>);前面main

也是如此mergeSort

您还应该将调用完全限定sort(numbers.begin(), numbers.end());为,std::sort(numbers.begin(), numbers.end());和 , 相同。如果你不这样做,那么由于技术原因称为“ADL”,如果你愿意,你可以查找它,那么只有当你调用它的参数(迭代器)是 namespace 中的类时,调用才会编译。这取决于具体的实现,因此调用在某些编译器上不起作用。copyuniquestd

于 2012-05-26T22:18:03.280 回答
1

我同意@steve 在 main() 之前声明排序函数。

我认为这里的问题是您正在sort()使用参数调用函数,std::vector但是在函数的定义中您刚刚编写了接收参数的类型,您还应该为变量编写一些名称。例如。

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

我要指出的另一件事是,由于您已经number全局声明了向量,因此无需调用 like sort(number),因为函数会自动找到全局定义的向量number。所以基本上如果你想number全局定义向量,那么函数sort()应该是无参数的。

您还在任何地方都使用了范围,而是可以在s -std::之后添加一行#include

using namespace std;

我希望它有效!

于 2012-06-05T09:57:19.683 回答