Hello. This is a program I've been working on for a while, but now I got stuck into one thing. I want to sort my product names for example (Bed) for product 1, (Quilt) for product 2.. etc.. I want to sort them according to alphabetic order.
I want it to output it as:
Bed
Quilt
but since I am reading them from a file they are written as:
Quilt
Bed
Does anyone know how to order them? I have tried using character arrays but I failed to solve it. Here's my attempt:
void salesperson::sortProducts()
{
string test;
char a[10];
int i , j;
// test = Quilt;
a[0] = 'A';
for(i=0; i<10; i++) // it doesnt matter how many times it runs actually
{
productSold[i].getProductNumber(test);
//cout<<test<<endl; <--- this was to check if the output is correct, and it is, just not in alphabetic order.
for(j=i; j<10; j++)
{
if (test > a[i])
{
cout<<test<<endl; // -----> this causes a syntax error.. I know it's wrong but had to put something to show what I was trying.
}
}
}
}
#include <iostream>
#include <string>
#include <array>
#include <algorithm> //Bunch of algorithms, but in particular will we be using std::sort.
int main()
{
std::array<std::string, 5U> items;
std::cout << "Enter five strings:\n";
for (auto& item : items) {
std::cin >> item;
}
std::cout << "Here are the strings in sorted order: ";
//We use the function std::sort to sort the items.
//To which we use the version with an overload for a function, in this case a lambda for us.
std::sort(items.begin(), items.end(), [&](const std::string& left, const std::string& right) {
std::size_t leftIter = 0, rightIter = 0; //create some iterators.
std::size_t leftSize = left.size(), rightSize = right.size(); //get the sizes.
//loop so long as the iters have reached their size limits.
while (leftIter != leftSize && rightIter != rightSize) {
//Check if the leftiter doesn't equal the rightIter
if (left[leftIter] != right[rightIter]) {
//return whether or not the left string index is less than the current right string index.
return left[leftIter] < right[rightIter];
}
++leftIter;
++rightIter;
}
//otherwise swap if the size is bigger you can change this if you want to.
return leftSize < rightSize;
});
for (constauto& item : items) {
std::cout << item << '\n';
}
std::cin.get();
return 0;
}
OP: And here's my 2 cents, particularly looking at reading from file. Like @rabster, my code uses range loops, so make sure your compiler is C++11 compliant or use iterators:
My text file looks like this: (not in alphabetical order and some lines can have >1 string)
Problem is I cannot use vectors, because I am not allowed to (based on the rules of the assignment project). Also, what are Iters? I am guessing this is something I didn't take so I can't use that as well. Actually my text file looks like this: