Yeah, it's your typical homework help topic, but the problem is this is stuff we NEVER COVERED IN CLASS and it was NOT IN OUR BOOK, even our TA can't figure out why our professor assigned this to our 101 class.

I have a good chunk of it done, I think. The stuff we DID learn in class. But of course, the one part I don't know where to begin on (aka the one part that's not in our book at all or discussed in lecture) is the only part our TA was specifically told he could NOT help us with...

It involves functions and vectors. Basically we need to be able to sort a chunk of input like this:

3 4 2 5
1 5 2 5
1 6 3 2
2 4 5 6

So that it sorts it by whatever column that is specified, and if the value is the same in two or more rows, it goes onto sorting by the next column specified, and so on so forth. We just repeat it a bunch of times with a different column order and send it to an output file, actually a different output for each sort.

So here's the program so far:

//This part makes sense, the basic stuff
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include<iomanip>
using namespace std;

template<class t1, class t2, class t3, class t4, class t5, class t6>
void SORT
(vector<t1> ,vector<t2> ,vector<t3> ,vector<t4> ,vector<t5> ,vector<t6> );


template<class type>
void sort(const vector<type>&);

template<class type>
void print(vector<type> v);

//This part I knew, no question about it.
//Initializing everything to zero and getting it read and in the function
int main()
{
vector<string> AminoAcid(0);
vector<int> O(0);
vector<int> C(0);
vector<int> N(0);
vector<int> S(0);
vector<int> H(0);
int n;

ifstream fin("input.txt");
string test;

if(fin.fail())
{cerr<<"Problem opening file";}
else
{
string word;
int atoms;
int i = 0;
while(!fin.eof())
{
fin>>word;
AminoAcid.push_back(word);
fin>>atoms;
O.push_back(atoms);
fin>>atoms;
C.push_back(atoms);
fin>>atoms;
N.push_back(atoms);
fin>>atoms;
S.push_back(atoms);
fin>>atoms;
H.push_back(atoms);
i++;
}
n = i-1;
}
SORT(AminoAcid,O,C,N,S,H);

///Simply spitting back the values to see if I got the initial function stuff
// right, which I did.
for(int j = 0;j<n;j++)
{
cout<<setw(15)<<Amino[j]<<setw(10);
cout<<O[j]<<setw(10);
cout<<C[j]<<setw(10);
cout<<N[j]<<setw(10);
cout<<S[j]<<setw(10);
cout<<H[j]<<endl;
}


fin.close();
return 0;
}


/* FUNCTION SORT */

template<class t1, class t2,class t3,class t4, class t5, class t6>
void SORT(vector<t1> v1,vector<t2> v2,vector<t3> v3,vector<t4> v4,vector<t5> 
v5,vector<t6> v6)
{
sort(v2); 
print(v2);
// This is where we do that sorting I described above, but I have no idea HOW 
// to do that (TA gave us the two lines right above this comment line, but 
// I don't know how it relates or where to go from here at all) 
return;
}


// This is the part the TA COULD help me with, of course it had to be 
// what I already knew and similar to programs we've already covered...
template<class type>
void sort(vector<type>& x)
{
int n = x.size();
int hold;

// Implement selection sort algorithm.

for (int k = 0; k <= n - 2; k++) 
{
for (int j = k + 1; j <= n - 1; j++)
{
if (x[k] > x[j])
{
hold = x[j];
x[j] = x[k];
x[k] = hold;
}
}
}
}

// Another part the TA gave just today, but I'm not too sure how it relates....
template<class type>
void print(vector<type> v)
{
int n = v.size();

for( int i = 0; i < n-1; i++ )
{cout<<v[i]<<endl;}

}

So yeah. I just don't know where to begin on that one part, nor what to look for in a tutorial... I just keep getting how-to guides on sorting just one vector. I just don't know how to get the input from the first part sorted..

As the code stands now it gives errors, which doesn't surprise me. Probably due to the fact that just that one piece is missing, really. But here it is in case it's something more:

c:\documents and settings\chris\my documents\ass4mod.cpp(72) : warning C4786: 'std::reverse_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > const *,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,st
d::basic_string<char,std::char_traits<char>,std::allocator<char> > const &,std::basic_string<char,std::char_traits<char>,std::allocator<char> > const *,int>' : identifier was truncated to '255' characters in the debug information
c:\documents and settings\chris\my documents\ass4mod.cpp(72) : warning C4786: 'std::reverse_iterator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > *,std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::bas
ic_string<char,std::char_traits<char>,std::allocator<char> > &,std::basic_string<char,std::char_traits<char>,std::allocator<char> > *,int>' : identifier was truncated to '255' characters in the debug information
c:\documents and settings\chris\my documents\ass4mod.cpp(80) : error C2065: 'v2' : undeclared identifier
c:\documents and settings\chris\my documents\ass4mod.cpp(56) : see reference to function template instantiation 'void __cdecl SORT(class std::vector<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >,clas
s std::allocator<class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > > >,class std::vector<int,class std::allocator<int> >,class std::vector<int,class std::allocator<int> >,class std::vector<int,class std::allocat
or<int> >,class std::vector<int,class std::allocator<int> >,class std::vector<int,class std::allocator<int> >)' being compiled
Error executing cl.exe.

1 error(s), 2 warning(s)

Also, once I get that one chunk of code... would I have to repeat the code X number of times for X different output files, or is there a way to put it in a loop but write to a different output file each time? If it's possible, I think I know what to do for it, but I'm more concerned with the program itself right now....

I've been working on this for quite a while so any help is greatly appriciated.

Dani AI

Generated

Short summary: the goal is to treat each horizontal row as a single record and sort whole records by an arbitrary priority list of columns (with tie-breakers). The simplest, safest approach is to stop juggling parallel vectors and either (A) pack each row into a single struct and sort a single vector<Row>, or (B) sort a vector of indices that reference the parallel vectors. Both let std::sort (or std::stable_sort) do the heavy lifting; this keeps rows intact and avoids error-prone manual element-swapping that appears in ’s attempts. (This also follows ’s and ’s suggestions to use the STL sort machinery, while respecting the “use vectors” constraint.)

A compact C++98-friendly pattern (pack rows + comparator that accepts a key-order) looks like this:

struct Row {
    std::string name;           // AminoAcid
    std::vector<int> vals;      // O,C,N,S,H stored as vals[0..4]
};

struct MultiKeyCompare {
    std::vector<int> order;     // e.g. {-1,0,1,2} where -1 means name first
    std::vector<bool> desc;     // same length: true = descending
    MultiKeyCompare(const std::vector<int>& o, const std::vector<bool>& d)
      : order(o), desc(d) {}
    bool operator()(const Row& a, const Row& b) const {
        for (size_t i = 0; i < order.size(); ++i) {
            int k = order[i];
            if (k == -1) {                // compare name
                if (a.name != b.name) return desc[i] ? a.name > b.name : a.name < b.name;
            } else {                      // compare numeric column
                if (a.vals[k] != b.vals[k]) return desc[i] ? a.vals[k] > b.vals[k] : a.vals[k] < b.vals[k];
            }
        }
        return false;
    }
};

Alternative: build an index array idx = {0..n-1} and sort idx with a comparator that reads the parallel vectors (O[idx[a]], Amino[idx[a]], ...). After sorting, either write output in idx order or apply the permutation to all parallel vectors. That is handy if preserving the original order for multiple different sorts is required (sort copies or re-sort idx for each order rather than destructively reordering the source).

Troubleshooting / practical tips:

  • Prefer std::sort (O(n log n)) or stable_sort if doing multi-pass key-by-key sorts from least- to most-significant key.
  • Fix I/O loop to use while(fin >> word >> a >> b >> c >> d >> e) rather than while(!fin.eof()).
  • Pass big containers by reference to avoid copies (e.g., SORT(vector<Row>& rows)).
  • Watch for common syntax bugs seen in the thread: stray semicolons after if, using assignment (=) instead of equality (==).
  • For multiple output files, keep an original container and either sort a copy or re-sort an index vector for each column-order, writing each result to a separate file.

This keeps the code readable, avoids fragile nested-conditionals, and makes implementing arbitrary column-priority orders straightforward.

Recommended Answers

All 6 Replies

Will this work to begin sorting in descending order by vector?

if (int y = 0; int z = 1; O[y] > O[z]; y++; z++;)
		{
		return 1;
		}
	
else if (O[y] < O[z];)
		{
		return -1;
		}
else { if (Amino[y] > Amino[z];)
			{
				return 1;
			}
		else if (Amino[y] < Amino[z];)
			{
			return -1;
			}
		else { if (C[y] < C[z];)

Or do I need to do something radically different?

Do you have to use vector?
If you can use list instead, that has built-in sorting functionality, all you need is to pass the sort function of list a pointer to a boolean function that compares 2 elements.

Yeah, we have to use vectors - that's about the only certain bit of info we were given.

This is what I have now, and it looks promising (if not lenghty...)

for (z == size() );

{
int y = 0;
int z = 1;
int c;

if (O[y] > O[z]);
		{
			c = 1;
			return 0;
		}
	
else if (O[y] < O[z]);
		{
			c = -1;
			return 0;
		}
else { if (Amino[y] > Amino[z]);
			{
				c = 1;
				return 0;
			}
		else if (Amino[y] < Amino[z]);
			{
				c = -1;
				return 0;
			}
		else { if (C[y] > C[z]);
				{
					c = 1;
					return 0;
				}
				else if (C[y] < C[z]);
				{
					c = -1;		
					return 0;
				}
				else { if (N[y] > N[z]);
						{
							c = 1;
							return 0;
						}
						else if (N[y] < N[z]);
							{
								c = -1;
								return 0;
							}
						else {if (S[y] > S[z]);
								{
									c = 1;
									return 0;
								}
								else if (S[y] < S[z]);
									{
										return 0;
									}
								else {if (H[y] > H[z]);
										{
											c = 1;									
											return 0;
										}
										else if (H[y] < H[z]);
											{
												c = -1;
												return 0;
											}




if (c = -1);
			{
			hold = O[z];
			O[z] = O[y];
			O[y] = hold;

			hold = Amino[z];
			Amino[z] = Amino[y];
			Amino[y] = hold;

			hold = C[z];
			C[z] = C[y];
			C[y] = hold;

			hold = N[z];
			N[z] = N[y];
			N[y] = hold;

			hold = S[z];
			S[z] = S[y];
			S[y] = hold;

			hold = H[z];
			H[z] = H[y];
			H[y] = hold;

			}
		}
	}
y++;
z++;
return 0;
}

Does this look about right to sort in descending order yet keep the horizontal rows the same (merely shifting their position)?

The only reason I'm hesitant to try it out is I have to do 6 iterations of this sorting order, and it'll get really long REALLY fast so there must be a shorter way.

Not to mention, I'm not sure where exactly this is supposed to go in my program other than "towards the bottom..." part of me doesn't want to monkey around with what I was already given but it doesn't seem to work otherwise..

Deeply nested conditionals always tick me off. There's always (well, almost) a better (read, cleaner) way of doing things.

Another chunk of code based off some help I was given:

#include <algorithm>
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <string>
using namespace std;

int main()
{
vector<string> Amino(0);
vector<int> O(0);
vector<int> C(0);
vector<int> N(0);
vector<int> S(0);
vector<int> H(0);
int n;

struct row
{
    std::string m_1;
    int m_2;
    int m_3;
    int m_4;
    int m_5;

    bool const operator<(row const & r) const
    {
        for (z =< size() );

{
int y = 0;
int z = 1;
int c;

if (O[y] > O[z]);
		{
			c = 1;
			return 0;
		}
	
else if (O[y] < O[z]);
		{
			c = -1;
			return 0;
		}
else { if (Amino[y] > Amino[z]);
			{
				c = 1;
				return 0;
			}
		else if (Amino[y] < Amino[z]);
			{
				c = -1;
				return 0;
			}
		else { if (C[y] > C[z]);
				{
					c = 1;
					return 0;
				}
				else if (C[y] < C[z]);
				{
					c = -1;		
					return 0;
				}
				else { if (N[y] > N[z]);
						{
							c = 1;
							return 0;
						}
						else if (N[y] < N[z]);
							{
								c = -1;
								return 0;
							}
						else {if (S[y] > S[z]);
								{
									c = 1;
									return 0;
								}
								else if (S[y] < S[z]);
									{
										return 0;
									}
								else {if (H[y] > H[z]);
										{
											c = 1;									
											return 0;
										}
										else if (H[y] < H[z]);
											{
												c = -1;
												return 0;
											}
								}
    }
				}
				}

};

typedef std::vector<row> rows;

template<typename container_type>
void my_sort(container_type & c)
{
    if (c = -1);
			{
			hold = O[z];
			O[z] = O[y];
			O[y] = hold;

			hold = Amino[z];
			Amino[z] = Amino[y];
			Amino[y] = hold;

			hold = C[z];
			C[z] = C[y];
			C[y] = hold;

			hold = N[z];
			N[z] = N[y];
			N[y] = hold;

			hold = S[z];
			S[z] = S[y];
			S[y] = hold;

			hold = H[z];
			H[z] = H[y];
			H[y] = hold;

			}
		}
	}
y++;
z++;
return 0;

}

void print_predicate(row const & r)
{
    std::cout 
         << r.m_1 << " "
         << r.m_2 << " "
         << r.m_3 << " "
         << r.m_4 << " "
         << r.m_5 << std::endl;
}

int main(int, char*)
{
    rows l_rows;
    ifstream fin("AAM.txt");
string test;

if(fin.fail())
	{cerr<<"Problem opening file";}
else
{
	string word;
	int atoms;
	int i = 0;
	while(!fin.eof())
	{
		fin>>word;
	    Amino.push_back(word);
		fin>>atoms;
		O.push_back(atoms);
		fin>>atoms;
		C.push_back(atoms);
		fin>>atoms;
		N.push_back(atoms);
		fin>>atoms;
		S.push_back(atoms);
		fin>>atoms;
		H.push_back(atoms);
		i++;
	}
	n = i-1;
}
    my_sort(l_rows);

    std::for_each(l_rows.begin(), l_rows.end(), print_predicate);
	fin.close();
return 0;
}

Only error I get is "unexpected end of file" but other than that, will this give me what I want?

Have you thought of using the sort algorithm in the stl, and a compare func

struct containerCompare
{
bool operator()(const Type& p1, const Type& p2) const
{

//compare your elements here
}
};


std::sort(container.begin(),container.end(),containerCompare());

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.