根据用户输入排序或合并

时间:2012-05-26 22:13:36

标签: c++

我试图根据用户输入调用一个函数。我无法弄清楚我做错了什么。我一直收到这个错误

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 个答案:

答案 0 :(得分:2)

在调用之前,您需要声明sort函数。将其定义移至main之上,或将void sort(std::vector<int>);置于main之前。

同样适用于mergeSort

您还应该将通话sort(numbers.begin(), numbers.end());完全限定为std::sort(numbers.begin(), numbers.end());copyunique也是如此。如果你不这样做,那么出于技术原因称为“ADL”,如果你愿意可以查找,那么只有当你调用它的参数(迭代器)是名称空间{{1}中的类时,调用才会编译}}。具体实现取决于它们是否存在,因此该调用不适用于某些编译器。

答案 1 :(得分:1)

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

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

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

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

您到处都使用了范围sort(),而只需在std:: s之后添加一行 -

#include

我希望它有效!

相关问题