Hello, I have asked a similar question before, but this one is slightly different.
If I have a vector of structures vector<S>, it is possible to use std::sort in order to sort this vector according to only one of the elements of the struct S, and this is can be done by passing a comparison function as the third argument of std::sort.
For example, here is the code that sorts vector<S> by inserting a lambda function to control std::sort:
Now my question is this: Just as we could sort vector<S> by using std::sort as described above, is there a way to use std::copy to copy ONLY according to one of the "coordinates" of S (for example the element myInt of S in the program above) from the vector<S> onto another vector<int>? In other words, can we use some version of std::copy to take the projection of vector<S> onto vector<int> by copying vec.myInt elements onto vector<int> tempIntVec?Code:// sort algorithm example #include <iostream> // std::cout #include <algorithm> // std::sort #include <vector> // std::vector #include <string> struct S { int myInt; float myFloat; string myString; }; int main () { vector<S> vec; vector<S> copyOfVec; S tempS; for(int k=0; k<10; k++){ tempS.myInt= k; tempS.myFloat=(float)( sqrt(2.0)+k); tempS.myString=to_string(k*20); // this std function converts numbers to string, but it is new, and exists only in C++0x vec.push_back(tempS); } copyOfVec.resize(vec.size()); copy(vec.begin(), vec.end(), copyOfVec.begin() ); // copy vec onto copyOfVec starting at the beginning of copyOfVec sort(copyOfVec.begin(), copyOfVec.end(), [](const S & S1, const S & S2){ return( S1.myInt > S2.myInt ) ; } ) ; // note the greater than sign ">" to make descending order for(int k=0; k<vec.size(); k++){ cout<< " vec[k].myInt = " << vec[k].myInt << endl; } cout <<" ----------------- " << endl; for(int k = 0; k<copyOfVec.size(); k++){ cout << " copyOfVec[k].myInt = " << copyOfVec[k].myInt << endl; } return 0; }
Many thanks.