3

What I currently have is:

std::vector<char> test = {'a', 'f', 'b', 'g', 'c', 'K', 'E'};

int smallest;
for ( int i = 0; i < test.size() - 1; i++)
{
    smallest = i;
    for (int j = i + 1; j < test.size(); j++ )
    {
        if (test[j] < test[smallest])
            smallest = j;
    }
    int temp = test[smallest];
    test[smallest] = test[i];
    test[i] = temp;
}

Which sorts vector test as: {E,K,a,b,c,f,g}. However, I want to treat uppercase and lowercase letters as equals so the end result instead is: {a,b,c,E,f,g,K}. What would be best way to achieve this? I guess one way would be to reset all the values of either the capital or lowercase letters to equal each other.

Olivia
  • 51
  • 4
  • 2
    essentially your question is a duplicate of [this](http://stackoverflow.com/questions/1380463/sorting-a-vector-of-custom-objects). You just need to write a compare function/funtor/lambda that ignores case when comparing letters. `tolower` or `toupper` make that easy. – NathanOliver Sep 08 '16 at 19:42

3 Answers3

5

The best way would be to use std::sort from <algorithm> as such:

std::sort(v.begin(), v.end(), [](char i, char j){ return std::tolower(i) < std::tolower(j); });

where v is the vector and std::tolower can be found in <cctype>. If you don't have access to C++11 lambdas, it can easily be replaced.

DeiDei
  • 10,205
  • 6
  • 55
  • 80
2

You can use std::sort with your own custom comparator, which uses std::tolower on each letter to do a case-insensitive comparison

#include <algorithm>
#include <cctype>
#include <iostream>
#include <vector>

int main()
{
    std::vector<char> test = {'a', 'f', 'b', 'g', 'c', 'K', 'E'};

    std::sort(begin(test),
              end(test),
              [](char lhs, char rhs)
              {
                  return std::tolower(lhs) < std::tolower(rhs);
              });

    for (auto letter: test)
    {
        std::cout << letter << std::endl;
    }
}

Live demo

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

While everyone else has suggested std::sort in their answer, I will suggest a solution with your algorithm, like this. (You will need std::tolower or std::toupper):

std::vector<char> test = {'a', 'f', 'b', 'g', 'c', 'K', 'E'};

int smallest;
for ( int i = 0; i < test.size() - 1; i++)
{
    smallest = i;
    for (int j = i + 1; j < test.size(); j++ )
    {
        if (std::tolower(test[j]) < std::tolower(test[smallest])) //Or use std::toupper
            smallest = j;
    }
    int temp = test[smallest];
    test[smallest] = test[i];
    test[i] = temp;
}
Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88