다음 코드를 갖는C++ : STL : 설정 : 저장된 값을 const와
#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
이 값을으로 저장한다는 것을 알고 있습니다.여기서 K는 키이고 V는 값입니다. 우리는 K 객체를 변경할 수 없습니다. 그러나 set<T>
과 multiset<T>
은 이 아닌 T
으로 개체를 저장합니다. 그래서 나는 왜이 성모가 필요합니까 ??
사실, 나는'set' * 값을 쉽게 수정할 수 없도록 ('const'로) 저장한다고 생각합니다. 값을 수정하면 항목이 세트의 잘못된 위치에있을 가능성이 있으므로 항목 수정을 허용하지 않습니다. –
'std :: unary_function'은 2011 년에 더 이상 사용되지 않으므로 어쨌든 펑터를 람다로 바꾸는 것이 좋습니다. – pmr
이것은'set'을 잘못된 방법으로 사용하고 있다는 경고입니다. 레코드에는 키와 값이 있지만'map' 대신'set'에 저장합니다. – Omnifarious