有以下代码:C++:STL:集合:存储值常量性
#include <iostream>
#include <set>
#include <string>
#include <functional>
using namespace std;
class Employee {
// ...
int _id;
string _name;
string _title;
public:
Employee(int id): _id(id) {}
string const &name() const { return _name; }
void setName(string const &newName) { _name = newName; }
string const &title() const { return _title; }
void setTitle(string const &newTitle) { _title = newTitle; }
int id() const { return _id; }
};
struct compEmployeesByID: public binary_function<Employee, Employee, bool> {
bool operator()(Employee const &lhs, Employee const &rhs) {
return lhs.id() < rhs.id();
}
};
int wmain() {
Employee emplArr[] = {0, 1, 2, 3, 4};
set<Employee, compEmployeesByID> employees(emplArr, emplArr + sizeof emplArr/sizeof emplArr[0]);
// ...
set<Employee, compEmployeesByID>::iterator iter = employees.find(2);
if (iter != employees.end())
iter->setTitle("Supervisor");
return 0;
}
我不能编译具有该代码(MSVCPP 11.0):
1> main.cpp
1>d:\docs\programming\test01\test01\main.cpp(40): error C2662: 'Employee::setTitle' : cannot convert 'this' pointer from 'const Employee' to 'Employee &'
1> Conversion loses qualifiers
这有助于编译:
if (iter != employees.end())
const_cast<Employee &>(*iter).setTitle("Supervisor");
问题:我知道map
和multimap
将它们的值存储为pair(const K, V)
其中K是一个键,V是一个值。我们不能改变K对象。但是set<T>
和multiset<T>
将其对象存储为T
,而不是const T
。那么为什么我需要这个CONST CAST?
实际上,我认为'set's * do *存储了它们的值,以至于它们不容易修改(实际上就是'const')。如果您修改了一个值,那么该项目可能位于该集合中的错误位置,因此允许修改该项目是没有意义的。 – 2012-01-16 22:26:26
'std :: unary_function'在2011年已被弃用,您可能希望用lambda替换函子。 – pmr 2012-01-16 22:34:26
这是一个警告,您正在以错误的方式使用'set'。你的记录有键和值,但你将它们存储在'set'而不是'map'中。 – Omnifarious 2012-01-16 22:49:10