Skip to content

Instantly share code, notes, and snippets.

@joshpeterson
Created July 25, 2010 15:48
Show Gist options
  • Save joshpeterson/489648 to your computer and use it in GitHub Desktop.
Save joshpeterson/489648 to your computer and use it in GitHub Desktop.
Reverse a list of string in C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
// Reverse the elements in a vector.
template <typename T>
std::vector<T> Reverse(std::vector<T> input)
{
std::vector<T> output;
std::copy(input.rbegin(), input.rend(), std::back_inserter(output));
return output;
}
// Validate that two collections have the contents.
template <typename ExpectedIteratorType, typename ActualIteratorType>
void ValidateListsHaveTheSameElements(ExpectedIteratorType expectedBegin, ExpectedIteratorType expectedEnd, ActualIteratorType actualBegin, ActualIteratorType actualEnd)
{
size_t numberOfExpected = std::distance(expectedBegin, expectedEnd);
size_t numberOfActual = std::distance(actualBegin, actualEnd);
if (numberOfExpected != numberOfActual)
{
std::cout << "Difference found - The number of expected elements is " << numberOfExpected << " the number of actual elements is " << numberOfActual << std::endl;
}
ExpectedIteratorType expected = expectedBegin;
ActualIteratorType actual = actualBegin;
for (; expected != expectedEnd && actual != actualEnd; ++expected, ++actual)
{
if (*expected != *actual)
{
std::cout << "Difference found - expected: " << *expected << " actual: " << *actual << std::endl;
break;
}
}
}
void main()
{
std::vector<std::string> input;
input.push_back("The");
input.push_back("quick");
input.push_back("brown");
input.push_back("fox");
std::vector<std::string> actual = Reverse(input);
std::string expected[] = { "fox", "brown", "quick", "The" };
ValidateListsHaveTheSameElements(&expected[0], &expected[4], actual.begin(), actual.end());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment