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?
Thanks in advance.
Printable View
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?
Thanks in advance.
Hmmm, not sure what convenient means. But you can use the STL algorithm sort() to sort a vector.
[edit]
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]
Can you provide me with a short example?
I've tried:
and I get an error statingCode:vector<int>v;
v.push_back(7);
v.push_back(5);
v.push_back(6);
v.sort();
"sort not a memeber of vector<int, allocater<int>>"
or something like that.
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());
Is it possible to
sort(v.end(), v.begin()); ?
I get no compile error when I try it, but no results either.
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.
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;
}