'why does std::map need an operator< and how do I write one
I was working with the std::map library and I am trying to put a bunch of data into a map, I created a map to hold a date(time_t) and a float but when I try to add them in, my complier tells me "error: no match for 'operator<' (operand types are const &date, const &date)"
I tried creating an overloaded < operator, but still gave me the same error. I also tried to create a map outside of this program, and that did not need an operator< so how do I write this, and why is it even necessary?
here is the class that I am running it in:
class MutualFund
{
private:
std::string ticker;
Date oldestDate; //optional
Date newestDate; // optional
float newestNav; //optional
map<Date,float> navHistory;
set<Dividend> divHistory;
public:
MutualFund(string i)
{
if( i == "VTSMX")
{
ifstream temp;
string cell,cell2,tempstring;
int i = 1;
float tempFloat;
temp.open("C:\\Users\\Lukas PC\\Desktop\\ass6files\\VTSMXshuffled.csv");
//what needs to be done here:
// turn the cell 1 into a Date object by turning it into a time_t
//turn the cell2 into a float
//populate the map
while(!temp.eof())
{
// get the numbers from the spreadsheet
getline(temp,cell,',');
getline(temp,cell2,',');
getline(temp,tempstring);
//make a time_t object from cell and put it into a Date object
struct std::tm tm = {0};
std::istringstream ss(cell.c_str());
ss >> std::get_time(&tm, "%Y-%m-%d");
//tm.tm_mday = (tm.tm_mday -1);
std::time_t time = mktime(&tm);
Date mapDate;
mapDate.setDate(time);
//turn cell2 into a float
if(isalpha(cell.at(1)) && isalpha(cell2.at(1)))
{
}
else
{
cell2.erase(5,20);
//cout << cell2<< endl;
std::string::size_type sz;
tempFloat = stof(cell2,&sz);
navHistory[mapDate] = tempFloat;
}
i++;
}
}
else if (i == "VFINX")
{
}
}
friend const bool operator< ( const Date &lhs ,const Date &rhs)
{
return true;
}
};
Thanks for your help! always appreciated.
Solution 1:[1]
The reason std::map requires a less than operator is because it is implemented as a red black tree. Not only that, but the elements in a map are guaranteed to be ordered. Thus, it requires that the type it is referencing as the key be comparable via operator<.
If you don't need the elements to be ordered then you could use std::unordered_map. However, for user defined types you would have to explicitly define and overload std::hash.
With just one of operators overloaded it can determine if one is greater or if they are both equal.
Anyways, the issue with your code is the fact that you are trying to create the less than operator outside the main class. Move the overloaded operator< inside of the Date class and it should work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
