There was another thread about this (http://www.daniweb.com/forums/thread114737.html) but it didn't seem to be resolved?

If I have a vector of int's and another vector of the same length of corresponding names, I would like to sort the ints and have the names "follow"

vector<string> Doubles;
	Doubles.push_back("Name1");
	Doubles.push_back("Name2");
	Doubles.push_back("Name3");

	vector<int> Ints;
	Ints.push_back(4);
	Ints.push_back(1);
	Ints.push_back(7);

	sort(Ints.begin(), Ints.end());

	for(int i = 0; i < Ints.size(); i++)
	{
		cout << Ints[i] << endl;
	}

Now I would like the names to be sorted in the same order, ie. Name2, Name1, Name3.

There is a 3rd parameter of the sort() function, but I don't understand how to use it. Can someone shed some light?

Thanks,

Dave

HA! I just noticed that was my thread lol. I still really can't believe that there is no built in mechanism to do this??

It is very easy if you combine the two into a struct as Ancient Dragon suggested (full code listing below). However it still seems reasonable to ask for the indexes of the sort (as you can do in Matlab if anyone is familiar with that) rather than just the resulting sorted vector.

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>


using namespace std;

struct NumberName
{
	int index;
	string Name;
};

bool operator<(NumberName NN1, NumberName NN2)
{
	return NN1.index < NN2.index;
}

int main (int argc, char *argv[]) 
{
	vector<string> Names;
	Names.push_back("Name1");
	Names.push_back("Name2");
	Names.push_back("Name3");

	vector<int> Ints;
	Ints.push_back(4);
	Ints.push_back(1);
	Ints.push_back(7);

	vector<NumberName> Pairs(Names.size());
	for(int i = 0; i < Names.size(); i++)
	{
		Pairs[i].index = Ints[i];
		Pairs[i].Name = Names[i];
	}

	sort(Pairs.begin(), Pairs.end());

	for(int i = 0; i < Pairs.size(); i++)
	{
		cout << Pairs[i].index << " " << Pairs[i].Name << endl;
	}
	return 0;
}

isn't it possible to use a map rather than using two separate vectors? Then, I think, the entire problem will be solved.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.