I am pretty inexperienced in C++ and I have a very strange problem when sorting a vector which is of type "T" that is a class member/attribute in a template class. The program compiles and run but calling "sort" over that attribute does work properly: it is not ordered at all after calling. However, I can create a local vector of type T inside a method and get ir ordered properly. What am I doing wrong?
I also include a simple and fast example of this situation. This is the template class (TempClass.h):
#include <vector>
#include <stdio.h>
#include <algorithm>
#include <functional>
template <class T> class TempClass{
public:
TempClass(T a, T b, T c){
container.clear();
container.reserve(3);
container[0] = a; container[1] = b; container[2] = c;
}
void modifyAttribute(){
printf("Previous state:\n");
for(int i = 0; i<3; i++){
printf("[%d] -> %d\n", i, container[i].read());
}
sort(container.begin(), container.end(), std::greater<T>());
printf("Final state:\n");
for(int i = 0; i<3; i++){
printf("[%d] -> %d\n", i, container[i].read());
}
}
void testLocally(){
std::vector<T> localContainer(3);
localContainer[0] = T(14); localContainer[1] = T(97); localContainer[2] = T(42);
printf("Previous state:\n");
for(int i = 0; i<3; i++){
printf("[%d] -> %d\n", i, localContainer[i].read());
}
sort(localContainer.begin(), localContainer.end(), std::greater<T>());
printf("Final state:\n");
for(int i = 0; i<3; i++){
printf("[%d] -> %d\n", i, localContainer[i].read());
}
}
private:
std::vector<T> container;
};
And a possible simple usage of it (Tester.cpp):
#include "TempClass.h"
class Value{
public:
Value(){
this->val = 0;
}
Value(int val){
this->val = val;
}
Value(const Value& reference){
this-> val = reference.val;
}
bool operator >(const Value& other) const{
printf("Ok...\n");
return this->val > other.val;
}
int read(){
return this->val;
}
private:
int val;
};
int main(){
TempClass<Value> object(Value(6), Value(17), Value(43));
object.testLocally();
object.modifyAttribute();
return 0;
}
I do not really know what is happening :( Thank you very much in advance for your help.
Regards