我知道STL容器中的对象有“可分配和可复制构造”的要求。例如,您不能将具有const成员的对象放入向量中。
#include <vector>
// /home/doriad/Test/Test.cxx:3:8: error: non-static const member ‘const int MyClass::x’, can’t use default assignment operator
// struct MyClass
// {
// int const x;
// MyClass(int x): x(x) {}
// };
//
// int main()
// {
// std::vector<MyClass> vec;
// vec.push_back(MyClass(3));
// return 0;
// }
但是,我注意到它可以与std :: set一起使用:
#include <set>
// Attempt 1
struct MyClass
{
int const x;
MyClass(int x): x(x) {}
bool operator< (const MyClass &other) const;
};
bool MyClass::operator<(const MyClass &other) const
{
if(this->x < other.x)
{
return true;
}
else if (other.x < this->x)
{
return false;
}
}
int main()
{
std::set<MyClass> container;
container.insert(MyClass(3));
return 0;
}
这仅适用于某些编译器吗?还是可以这样做?
谢谢,
大卫
Well from the link, the assignment operator requirement is only for "output iterators" where the expression
*it = a;
must be valid. BTW, the iterators for the std::set container are not output iterators. So, that shouldn't be a problem.但是迭代器还不是全部,您需要注意容器可以做什么。人们经常说任何容器的值类型必须是CopyAssignable和CopyConstructible。好吧,这是对现实的过度简化。如果希望使用容器可以进行所有操作,那么可以,您需要满足这些要求。但是实际上需要拷贝可分配值类型的操作实际上并不多,特别是对于std :: set(其原理是,其键值在初始插入后必须保持不变)。对于std :: set,我能发现的唯一真正需要复制可分配(或移动可分配)值的操作是容器本身的赋值运算符。
This argument goes for the other containers, the C++ standard specifies the requirements on the value-type on a per-function basis on the containers (e.g. if you want to do
insert()
in a vector container you need a MoveConstructible and MoveAssignable value type, etc.). This makes sense since containers are class templates for which only the functions that are used are actually instantiated, so, the requirements on the value type is just the addition of the requirements of all the functionality of the container that you actually use in your code. Generally, all the "link-list" or "tree" type containers don't require CopyAssignable or MoveAssignable value types for much of anything since they, by design, avoid doing copying as much as possible.以上是理论。在实践中,我不确定在容器的实际实现方面对值类型的要求有多精细,但是我看不出有什么理由比标准规定的要少。当然,您可能会感到惊讶。以我的经验,当您将容器用作不可变值的不可变容器时,如果值类型为const(或不可分配)就可以。
Hm, this might be the answer?
http://www.cplusplus.com/reference/std/iterator/
看起来赋值运算符要求仅适用于随机访问迭代器?