2017-06-03 47 views
0

传递当试图在功能partitionk(),我得到的错误交换()函数不工作通过引用C++

“的错误使用交换()的矢量对象上:请求构件‘交换’在'(& num_list) - > std :: vector < _Tp,_Alloc> ::运算符[]>(((std :: vector :: size_type)endn))',它是非类类型'__gnu_cxx :: __alloc_traits> :: value_type的{又名INT}“|”`

enter code here 

#include <iostream> 
#include <vector> 
#include <unordered_map> 
#include <cstdlib> 
using namespace std; 

int partitionk(vector<int>& num_list , int start, int endn ) { 
     int pindex = start; 
     int rand_num = rand() % endn; 
     num_list[endn].swap(num_list[rand_num]); // getting error 

     for (int i = 1 ; i < endn ; i++){ 
      if (num_list[i] < num_list[endn]){ 
       num_list[i].swap(num_list[pindex]); // getting error 
       pindex += 1; 
      } 
     } 
     num_list[endn].swap(num_list[pindex]);  // getting error 
     return pindex; 
} 

void quick_sort(vector<int>& num_list , int start, int endn ){ 
     if (start >= endn) return ; 

     else{ 
      int index = partitionk( num_list , start, endn ) ; 

       quick_sort(num_list , start, index); 
      quick_sort(num_list , index+1, endn ); 

     } 
} 

int main() 
{ 
    vector <int> nums= {4,7,1,3,9,5}; 
    quick_sort(nums , 0 , nums.size()-1); 

    for (auto i : nums){ 
     cout << i << " "; 
    } 

} 
+0

'num_list [endn]'是一个'int',它没有任何成员函数,但你试着对它调用'swap'。你在做什么? – DeiDei

回答

0

使用std::swap()

std::swap(num_list[endn], num_list[num]]; 

向量成员swap()是用于交换entire vectors。并且您使用swap()会尝试调用矢量项的交换成员,即int:此类型没有swap()