This shouldn't compile (and it doesn't for me). x is out of scope on line 9. What is "less than" something else? Is {5,3} less than {3,4}? Or vice-versa? I don't know what the default "less than" is, for one array being "less than" another, but you can't sort unless there is one. Make sure it's what you want. You may have to provide it.
Anyway, here is what I THINK you probably want. If not, you'll need to provide a less than comparison.
#include <vector>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;
int main()
{
/* The vector seems right if my output works,
this doesn't sort it though by person or pancake. */
srand(time(0));
vector< vector<int> > pVec(10,vector<int>(2));
for(int x=0; x < 10; x++){
pVec[x][0]= rand() % 25;;
pVec[x][1] = rand() % 25;
}
for (int x = 0; x < pVec.size(); ++x)
cout << "\nPerson "<< pVec[x][0] <<" ate " << pVec[x][1]<<" pancakes.";
sort(pVec.begin(), pVec.end());
cout << "Sorted\n";
for (int x = 0; x < pVec.size(); ++x)
cout << "\nPerson "<< pVec[x][0] <<" ate " << pVec[x][1]<<" pancakes.";
cin.get();
return 0;
}
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
:confused: You're really not making much sense.
It seems you want the "outer" vector sorted based on the contents of the "inner" vectors, and you want the contents of the inner vectors to be stable.
Is there a reason you are using vectors to store a specific "person"'s information? I think you may want to consider using a vector of structs instead of a 2-d vector:
struct Person {
int myID;
int amountEaten;
};
const int ATTENDEES = 5;
vector<Person> People(ATTENDEES);
for (int i = 0; i < ATTENDEES; ++i) {
//prompt user for input
(People[i]).myID = inputID;
(People[i]).amountEaten = inputAmount;
}
//perform sort
Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
Correct, you would have to write a custom less-than operator that returns true based on the result of a comparison of the values of Person::amountEaten.
Fbody
Posting Maven
2,930 posts since Oct 2009
Reputation Points: 833
Solved Threads: 393
>> Sorry no this is not the entire code my question is
sort(pVec.bgein(), pVec.end) doesn't sort ONLY the pVec[x][1] row, I need the numbers in pVec[x][0] to stay the same.
If pVec is a 2-D vector of integers, you're dereferencing it twice here, so it seems to me there is no pVec[x][1] row, there is a pVec[x][1] element. Hence only one number. Hence nothing to sort unless I'm missing something. You might want to show the before and after of what you want to do.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711