假设我有一个默认构造函数的类.如何通过设置其大小和默认值来初始化构造函数中的队列.
class StandardClass
{};
// will initialize a vector with 5 default standard class
std::vector<StandardClass> vec(5, StandardClass());
Run Code Online (Sandbox Code Playgroud)
我如何对队列做同样的事情?
std::queue<StandardClass> que(5, StandardClass()); ???
Run Code Online (Sandbox Code Playgroud) 当类属性是可变的时,Std :: sort有效.例如,以下代码有效,矢量按预期按升序排序.
class PersonMutable
{
public:
PersonMutable(int age, std::string name):
Age(age),Name(name)
{
}
int Age;
std::string Name;
};
void TestSort()
{
std::vector<PersonMutable> people;
people.push_back(PersonMutable(24,"Kerry"));
people.push_back(PersonMutable(30,"Brian"));
people.push_back(PersonMutable(3,"James"));
people.push_back(PersonMutable(28,"Paul"));
std::sort(people.begin(),people.end(),
[](const PersonMutable& a, PersonMutable & b) -> bool
{
return a.Age < b.Age;
});
}
Run Code Online (Sandbox Code Playgroud)
但是,当使用不可变时,同一个类与std :: sort不兼容.
class PersonImmutable
{
public:
PersonImmutable(int age, std::string name):
Age(age),Name(name)
{
}
PersonImmutable& operator=(const PersonImmutable& a)
{
PersonImmutable b(a.Age,a.Name);
return b;
}
const int Age;
const std::string Name;
};
void TestSort()
{
std::vector<PersonImmutable> people; …Run Code Online (Sandbox Code Playgroud)