Reputation: 3
I am having trouble figuring out why this is not compiling. This is just the basic class declaration, constructor/destructor and other functions are left out. Message is also properly defined somewhere else.
#include <vector>
#include <map>
using namespace std;
class SmartCarrier {
map<string, vector <Message *>> accounts_map;
void SearchMessage() const;
};
When I try to assign m_iter with m_iter = accounts_map.find(account)
I get the error no operator "=" matches these operands. I double checked to make sure the map iterator was the same type as the actual map which it is. I'm not sure what is incorrect.
void SmartCarrier::SearchMessage() const {
string account;
map<string, vector<Message *>>::iterator m_iter;
cout << "Enter an account: ";
cin >> account;
try {
m_iter = accounts_map.find(account);
if (m_iter != accounts_map.end) {
//code to display account information
} else {
throw 'e';
}
} catch (char e) {
cout << "Error: Account not found\n";
}
}
Upvotes: 0
Views: 50
Reputation: 598279
SearchMessage()
is declared as const
, so its this
parameter is pointing at a const SmartCarrier
object, so its accounts_map
member is also const
. When find()
is called on a const map
, it returns a const_iterator
instead of an iterator
.
Also, accounts_map.end
needs to be accounts_map.end()
instead.
Also, using an exception the way you are is just wasted overhead that you can (and should) get rid of.
Try this:
void SmartCarrier::SearchMessage() const {
string account;
cout << "Enter an account: ";
cin >> account;
map<string, vector<Message *>>::const_iterator m_iter = accounts_map.find(account);
if (m_iter != accounts_map.end()) {
//code to display account information
} else {
cout << "Error: Account not found\n";
}
}
If you are using C++11 or later, consider using auto
instead of const_iterator
explicitly, that would also fix the error:
auto m_iter = accounts_map.find(account);
Upvotes: 2