Có, bạn có thể ... nhưng hãy cẩn thận. operator<
được định nghĩa theo con trỏ, không phải về mặt chỉ.
#include <memory>
#include <map>
#include <string>
#include <iostream>
int main() {
std::map<std::shared_ptr<std::string>,std::string> m;
std::shared_ptr<std::string> keyRef=std::make_shared<std::string>("Hello");
std::shared_ptr<std::string> key2Ref=std::make_shared<std::string>("Hello");
m[keyRef]="World";
std::cout << *keyRef << "=" << m[keyRef] << std::endl;
std::cout << *key2Ref << "=" << m[key2Ref] << std::endl;
}
in
Hello=World
Hello=
Lưu ý rằng nếu bạn sử dụng "răng cưa constructor" của 'std :: shared_ptr', tùy thuộc vào trường hợp sử dụng của bạn, bạn có thể muốn xem xét sử dụng [' std :: owner_less' ] (http://en.cppreference.com/w/cpp/memory/owner_less) là functor so sánh của bản đồ. Điều này sẽ giúp bạn đặt hàng dựa trên con trỏ đến toàn bộ đối tượng, thay vì subobject trực tiếp được trỏ đến bởi 'shared_ptr'. – tomjakubowski