我有一个包含n元素的向量.我需要m从矢量中随机选择一个元素子集而不重复.这样做最有效的方法是什么?我需要在我的代码中执行数千次这样的操作.
我脑海中的解决方案是rand()用来生成和k之间的随机数.然后选择向量中的第th个元素并将其插入到.继续这样做直到集合的大小变得相等.我现在确信该集合包含从元素集中随机选择的唯一元素.0nkstd::setmmn
其他可能的解决方案是什么?
谢谢.
我编写了以下代码来测试我对虚拟继承的理解.显然,我仍然没有完全得到它.这是我的代码(后跟我的问题):
#include <iostream>
#include <vector>
using namespace std;
class Foo
{
public:
virtual void foo();
void foo2();
};
void Foo::foo()
{
cout << "In FOO - foo 1" << endl;
foo2();
}
void Foo::foo2()
{
cout << "In FOO - foo 2" << endl;
}
class Bar : public Foo
{
public:
void foo();
void foo2();
};
void Bar::foo()
{
cout << "In BAR - foo 1" << endl;
foo2();
}
void Bar::foo2()
{
cout << "In BAR - foo …Run Code Online (Sandbox Code Playgroud) 说,我有一个字符串和一个bools 矢量.根据字符串中的字符,我想将相应的矢量索引设置为true.
std::vector<bool> is_present(256, false);
for (int i = 0; i < str.size(); ++i)
{
is_present[str[i]] = true;
}
Run Code Online (Sandbox Code Playgroud)
据我所知,标准没有定义char的签名.根据平台的不同,它可能是签名或未签名的.在大多数平台上,signed char将是一个8位二进制补码(-128到127),unsigned char将是一个8位无符号整数(0到255).
如果是这种情况,是否有可能str[i]返回负数并导致内存故障is_present[str[i]]?或者是char得到强制转换为vector<bool>::size_type它unsigned,因此不会发生问题?
另外,使用vector<bool> is_present(pow(2, CHAR_BIT)), false)而不是将其硬编码为256 更好吗?