He all
I am currently working a on a problem to convert the entire contents of an STL container into a string. For example if I had this:
int foo[] = {1, 2, 3, 4, 5};
vector<int> bar(foo, foo + 5);
I would like to convert bar
into the string "1 2 3 4 5". I decided to use templates with this so I could convert most of the STL containers. When writing my function for converting to a string I also created a class that takes a single element from the container and converts it to a string. The code that I have works the way I want it to right now. My question is I think I might have made this more complex than it needs to be but I'm trying to make it as flexible as I can. That's where the conversion class comes in. I think that it should be there so any type of data can be passed into the function and it can be converted. In my code I just wrote one for numbers.
// StringAndNumberConverter.h
#ifndef STRINGANDNUMBERCONVERTER_H
#define STRINGANDNUMBERCONVERTER_H
#include <sstream>
#include <string>
template <typename T>
std::string NumberToString(T number)
{
std::string output;
std::stringstream ss;
ss << number;
ss >> output;
return output;
}
#endif
// ContainerToString.h
#ifndef CONTAINERTOSTRING_H
#define CONTAINERTOSTRING_H
#include <string>
#include <functional>
#include "StringAndNumberConverter.h"
// converts single elements into strings
// can be used for all forms of numbers.
template<typename T>
class NumberConverter : std::unary_function<T, std::string>
{
public:
std::string operator()(T object)
{
return NumberToString(object); // simple stringstream conversion technique
}
};
// goes through the container and calls the ConvertFunction on each element
// then adds it to the builder string
template <typename RandomAcessIterator, typename ConvertFunction>
std::string ContainerToString(RandomAcessIterator first, RandomAcessIterator last, ConvertFunction function)
{
std::string builder;
while (first != last)
{
builder += function(*first) + " ";
first++;
}
builder.erase(builder.size() - 1, 1);
return builder;
}
#endif
// Main.cpp
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include "ContainerToString.h"
using namespace std;
int main()
{
double foo[] = {10.1, 20.2, 30.3, 40.4, 50.5};
vector<double> bar(foo, foo + 5);
string temp = ContainerToString(bar.begin(), bar.end(), NumberConverter<double>());
cout << temp;
cin.get();
return 0;
}
Thanks for taking your time to read this. All suggestions/criticisms are welcome.
Nathan