Monday 17 October 2016

c++ - Conversion from int* to int&




I've been trying to compile and have played around with the ampersands and still can't figure out what the error is. Any ideas?



qsort.cc:22:23: error: no matching function for call to ‘qsort::quicksort(std::vector >*)’
qsort.cc:22:23: note: candidate is:

qsort.h:16:6: note: void qsort::quicksort(std::vector&) [with T = int]
qsort.h:16:6: note: no known conversion for argument 1 from ‘std::vector >*’ to ‘std::vector >&’



Header:



template 
class qsort
{
public:

void quicksort(vector &v);
void qusort(vector &v, int left, int right);
void print(vector &v);

};

template
void qsort::quicksort(vector &v)
{
qusort(&v, 0, 0);
}

template
void qsort::print(vector &v)

{
for(int i = 0; i < v.size(); i++)
{
cout << v[i] << endl;
}
}


Main:




int main()
{
qsort asort;
vector v;

v.push_back(2);
v.push_back(1);
v.push_back(7);
v.push_back(3);
v.push_back(8);

v.push_back(4);
v.push_back(0);
v.push_back(9);
v.push_back(5);
v.push_back(6);

asort.quicksort(&v);
asort.print(&v);

return 0;

}


Updated errors after ampersand removed out of main function calls (the short version)



qsort.h: In member function ‘void quisort::qusort(std::vector&, int, int) [with T = int]’:
qsort.h:18:5: instantiated from ‘void quisort::quicksort(std::vector&) [with T = int]’



qsort.cc:22:22: instantiated from here
qsort.h:27:38: error: invalid conversion from ‘int’ to ‘const char*’ [-fpermissive]

/usr/include/c++/4.6/bits/basic_string.tcc:214:5: error: initializing argument 1 of ‘std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]’ [-fpermissive]



qsort.h:18:5: instantiated from ‘void quisort::quicksort(std::vector&) [with T = int]’
qsort.cc:22:22: instantiated from here
qsort.h:31:9: error: no match for ‘operator<’ in ‘(& v)->std::vector<_Tp, _Alloc>::operator[] [with _Tp = int, _Alloc = std::allocator, std::vector<_Tp, _Alloc>::reference = int&, std::vector<_Tp, _Alloc>::size_type = long unsigned int](((long unsigned int)i)) < pivot’
qsort.h:31:9: note: candidates are:
/usr/include/c++/4.6/bits/stl_pair.h:207:5: note: template bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&)
/usr/include/c++/4.6/bits/stl_iterator.h:291:5: note: template bool std::operator<(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)


Answer



Your member function takes the arguments by reference. They don't take pointers (that which is returned by the address operator &). You simply need to pass the object and the reference will bind:




asort.quicksort(v);
asort.print(v);

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...