在C++ 14中,关联容器似乎已从C++ 11改变 - [associative.reqmts]/13说:
成员函数模板
find,count,lower_bound,upper_bound,并且equal_range不得,除非类型参与重载决议Compare::is_transparent存在.
使比较器"透明"的目的是什么?
C++ 14还提供了这样的库模板:
template <class T = void> struct less {
constexpr bool operator()(const T& x, const T& y) const;
typedef T first_argument_type;
typedef T second_argument_type;
typedef bool result_type;
};
template <> struct less<void> {
template <class T, class U> auto operator()(T&& t, U&& u) const
-> decltype(std::forward<T>(t) < std::forward<U>(u));
typedef *unspecified* is_transparent;
};
Run Code Online (Sandbox Code Playgroud)
因此,例如,std::set<T, std::less<T>>将不会有一个透明的比较,而是std::set<T, std::less<>> …
我试图将一组整数中的项的默认顺序更改为lexicographic而不是numeric,并且我无法使用g ++进行以下编译:
file.cpp:
bool lex_compare(const int64_t &a, const int64_t &b)
{
stringstream s1,s2;
s1 << a;
s2 << b;
return s1.str() < s2.str();
}
void foo()
{
set<int64_t, lex_compare> s;
s.insert(1);
...
}
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error: type/value mismatch at argument 2 in template parameter list for ‘template<class _Key, class _Compare, class _Alloc> class std::set’
error: expected a type, got ‘lex_compare’
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
假设我有一组unique_ptr:
std::unordered_set <std::unique_ptr <MyClass>> my_set;
Run Code Online (Sandbox Code Playgroud)
我不确定检查集合中是否存在给定指针的安全方法是什么.这样做的正常方法可能是调用my_set.find (),但我作为参数传递什么?
我从外面得到的只是一个原始指针.所以我必须从指针创建另一个unique_ptr,将它传递给find()然后release()指针,否则对象将被破坏(两次).当然,这个过程可以在一个函数中完成,因此调用者可以传递原始指针并进行转换.
这种方法安全吗?有没有更好的方法来使用一组unique_ptr?
我想存储一堆键值对象,但值对象本身(及其对它的引用)知道它的键.我还想在只给出密钥的情况下有效地查找这些对象.
class SomeObject
{
private:
//String or integer. int seem cheap enough to duplicate with std::map, but
//strings seem pretty expensive when there may be thousands of objects in existence.
//Reference/Pointer to key is fine
const SomeOtherObject key;
...other stuff...
public:
...methods, some of which use the key in some way...
};
Run Code Online (Sandbox Code Playgroud)
有没有什么好方法可以避免const_cast下面的内容,同时保持const的正确性?
没有const_cast下面的代码不编译.set::find获取对set的键类型的const引用,因此在我们的例子中它保证不改变传入的指针值; 但是,没有任何保证不改变指针指向的内容.
class C {
public:
std::set<int*> m_set;
bool isPtrInSet(const int* ptr) const
{
return m_set.find(const_cast<int*>(ptr)) != m_set.end();
}
};
Run Code Online (Sandbox Code Playgroud) c++ ×5
stl ×3
c++-faq ×1
c++11 ×1
c++14 ×1
const ×1
const-cast ×1
containers ×1
dictionary ×1
set ×1
unique-ptr ×1