小编use*_*838的帖子

如何使用n个默认值初始化队列?

假设我有一个默认构造函数的类.如何通过设置其大小和默认值来初始化构造函数中的队列.

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)

c++ queue stl c++11

4
推荐指数
1
解决办法
5807
查看次数

为什么STL的std :: sort不能用于不可变类?

当类属性是可变的时,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)

c++ sorting stl c++11

1
推荐指数
1
解决办法
524
查看次数

标签 统计

c++ ×2

c++11 ×2

stl ×2

queue ×1

sorting ×1