使用向量对堆栈进行排序

Sort Stack using vector

我是堆栈和向量的新手。我正在尝试使用 vector 对堆栈进行排序,但遇到错误。请建议如何解决此错误

我的代码

/* The below method sorts the stack s 
you are required to complete the below method */
void SortedStack :: sort()
{
  vector<int> st;
  while(!s.empty()){
      st.push_back(s.top());
      s.pop();
  }
  
  sort(st.begin(),st.end());
  
    for (auto itr = st.begin(); itr != st.end(); ++itr) {
      s.push(*itr);
  }


}

产生错误

Compilation Error:
Compilation Error
prog.cpp: In member function ‘void SortedStack::sort()’:
prog.cpp:61:27: error: no matching function for call to ‘SortedStack::sort(std::vector<int>::iterator, std::vector<int>::iterator)’
   sort(st.begin(),st.end());
                           ^
prog.cpp:52:6: note: candidate: void SortedStack::sort()
 void SortedStack :: sort()
      ^
prog.cpp:52:6: note:   candidate expects 0 arguments, 2 provided

sort(st.begin(), st.end()); 试图调用您的 sort 函数,但编译失败,因为参数不正确。

std::sort(st.begin(), st.end()); 是一个微不足道的修复。

这个故事的寓意是始终明确使用std::,并放弃using namespace std;等。您的代码也变得更具可读性,因为它立即很明显,您正在使用标准库中的函数。