小编use*_*006的帖子

std :: async和std :: future行为

我试图了解异步行为,并写了一些愚蠢的测试程序.

int f(int i)
    {
        std::cout << i << ": hello" << std::endl;
        int j = 0;
        while (j < 10000) //just add some delay
        {
            j++;
        }
        return j;
    }

int main()
{
    for (int i = 0; i < 10000; i++)
    {
        std::async(std::launch::async, f, i);
    }
    std::cout << "in main" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

使用上面的代码,输出似乎完全同步.所有10000个线程似乎按顺序执行.主线程块.

0: hello
1: hello
2: hello
.......
10000: hello
in main
Run Code Online (Sandbox Code Playgroud)

但是,当返回的未来存储在向量中时,输出将全部损坏并且主要退出而不等待生成的线程.线程是否在此处分离?

int main()
{
    std::vector<std::future<int>> v;

    for (int i = 0; i < …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

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

打印 unordered_set 的元素

所以我正在编写一个小代码来删除字符串中的重复字符。我已经使用 map、vector 完成了它,但想使用 unordered_set。

#include <iostream>
#include <unordered_set>
#include <string.h>

using namespace std;

int main() {
    char* str = "abbcdeffg";
    std::unordered_set<char> ump;

    for(int i = 0; i < strlen(str) ; i++)
    {
        ump.insert(str[i]);
    }

    for (auto it = ump.begin(); it != ump.end(); ++it)
    {
        cout << *it;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,元素的打印顺序与其插入顺序相反。输出是 gfedcba。请问有人可以解释为什么吗?

以原始顺序打印元素的最佳方法是什么。unordered_set 中没有 operator--() 因为它有前向迭代器。

谢谢!

c++ c++11

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

指定范围的随机数的std :: discrete_distribution

我知道我可以这样使用std::discrete_distribution:

std::default_random_engine generator;
std::discrete_distribution<int> distribution {2,2,1,1,2,2,1,1,2,2};

int p[10]={};

for (int i=0; i<100; ++i) {
    int number = distribution(generator);
    ++p[number];
}
Run Code Online (Sandbox Code Playgroud)

但是,这将根据指定的重量生成0-9范围内的数字.

如何在用户指定的范围内生成数字,例如24-33或95-104等但仍然使用discrete_distribution中指定的分布,我该怎么办?

c++ random c++11 c++14

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

标签 统计

c++ ×3

c++11 ×3

c++14 ×1

random ×1