# vector to list?

• 01-06-2003
kes103
vector to list?
Is there a convenient way to convert a vector to a list?
If not, is there a convenient way to sort the items in a vector?
• 01-06-2003
Shiro
Hmmm, not sure what convenient means. But you can use the STL algorithm sort() to sort a vector.

Forget first question. Don't know if you mean this, but an easy algorithm: Take the first element of a vector and add it to a list, repeat this until all elements of the vector are processed.
[/edit]
• 01-06-2003
kes103
vector to list
Can you provide me with a short example?
I've tried:
Code:

```vector<int>v; v.push_back(7); v.push_back(5); v.push_back(6); v.sort();```
and I get an error stating
"sort not a memeber of vector<int, allocater<int>>"
or something like that.
• 01-06-2003
Shiro
Algorithm sort() is not a member of the vector template class.

Code:

```#include <vector> #include <algorithm> vector<int> v; v.push_back(7); v.push_back(5); v.push_back(6); sort(v.begin(), v.end());```
• 01-06-2003
kes103
Is it possible to

sort(v.end(), v.begin()); ?

I get no compile error when I try it, but no results either.
• 01-06-2003
Shiro
You get no compiler error, the algorithm sort expects to iterators for template class vector and gets them, so that is not wrong. But the function requires an iterator to the first element in range as first argument and an iterator to the last element as second argument, so I think that is why it doesn't work.
• 01-06-2003
hk_mp5kpdw
For the sort(v.end(),v.begin()); question, I am guessing you want to sort in descending order rather than ascending order. The default sorting method used by the sort function is to go through the elements from start to finish comparing the elements using the '<' operator. If you wish to override this, you can supply an optional third argument to the sort function which is a function that will compare two elements of the vector according to whatever criteria you wish. For example, the following will sort the vector in reverse order:
Code:

```#include <vector> #include <algorithm> using namespace std; bool MySort(const int& lhs,const int& rhs) {     return lhs > rhs;  // By itself, the sort algorithm will effectively use                       // lhs < rhs instead } int main() {     vector<int> v;     v.push_back(7);     v.push_back(5);     v.push_back(6);     sort( v.begin(), v.end(), MySort );     return 0; }```