This is an lab exercise for school, and I'm trying to figure out how to sort a pointer to vector of pointers to string. FileProcessor.h and Main.cpp cannot be modified, and it's from my professor. I'm working on FileProcessor.cpp, everything works except void FileProcessor::sortData(). I tried using the sort function although it doesn't work, i think cause it's pointing to a vector?
#include <string>
using std::string;
#include <vector>
using std::vector;
#ifndef FILEPROCESSOR_H
#define FILEPROCESSOR_H
class FileProcessor
{
public:
FileProcessor();
~FileProcessor();
void readFile(const string& fileName);
void sortData();
void writeFile(const string& fileName);
private:
string* fileName;
vector<string*>* namesPtr; // pointer to vector of pointers to string
class compareNames; // inner function class for use with STL sort
FileProcessor(const FileProcessor& rvalue); // not implemented
FileProcessor& operator=(const FileProcessor& rvalue); // not implemented
};
#endif
in your function: void FileProcessor::readFile(const string& fileName) you create an array of std::string*. Why? Why not just read into a single std::string and put that into your vector?
For your sort function, the problem is you don't want to sort the pointers which is what you are doing at the moment. You want to sort the things they point to.
So you need to pass a third parameter to std::sort():
The third parameter is a function that compares two elements of the vector. Those two elements are std::string pointers. So you need to bear that in mind when you compare them.
Generally, I would recommend having non-modifying operators as non-member functions, since they generally don't need access to the internals. (No one expects y=x+z to modify x or z). The operator example you found accesses internal members of the object, so it would have to be written differently to use a non-member version, unless those members are declared public.