# What is the output of this sort function?

IF
vector<int>   A;   // 10 elements, say 0-9
vector<long>   B;  // 10   elements, say all == 1
AND
struct SPredicate
{
const long* _rowBegin;
SPredicate(const vector<long>& v) : _rowBegin( v.begin() ) { }
bool operator()(int i, int j) { return _rowBegin[ i ]  <  _rowBegin[ j ] ; }
};
What would the ouput be of the following?
std::sort(A.begin(), A.end(),SPredicate(B));

###### Who is Participating?

Senior Software Engineer (Avast)Commented:
I believe this example code implements what your Q asks, yes? The output is what I stated I'd expect in my initial response, "...I'd expect that A would remain in the same order as it was initially"

Do you understand why this is the case though?
``````#include <vector>
#include <algorithm>
#include <iostream>

typedef std::vector<int> intvec_t;
typedef std::vector<long> longvec_t;

struct SPredicate
{
longvec_t::const_iterator _rowBegin;
SPredicate(longvec_t & v) : _rowBegin( v.begin() ) { }
bool operator()(int i, int j) { return _rowBegin[ i ]  <  _rowBegin[ j ] ; }
};

int main()
{
int  aA[] = {5,6,7,8,9,0,1,2,3,4};
long aB[] = {1,1,1,1,1,1,1,1,1,1};

intvec_t A(aA, (aA+10));
longvec_t B(aB, (aB+10));

std::sort(A.begin(), A.end(), SPredicate(B));

std::copy(A.begin(), A.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;

std::copy(B.begin(), B.end(), std::ostream_iterator<long>(std::cout, " "));
std::cout << std::endl;
}
``````
0

Senior Software Engineer (Avast)Commented:
The predicate is indexing B and comparing B using the current value of i and j (both of which will be values of A); however, all elements in B are 1 so I'd expect that A would remain in the same order as it was initially.
0

Senior Software Engineer (Avast)Commented:
^^^this assumes that the iterator of a vector is convertible to a type T *, which the C++ Standard doesn't as far as I can remember, define.
0

Author Commented:
Thanks for quick resonse
0

Author Commented:
yes. I was only unclear about where i , j came from in the comparison.
This method is a compact way to order set A elements based on the ordering of set B
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.