C++从随机函数中移除元素
C++ removing elements from random function
我想创建一个2D array a[5][5]
,其中没有两个相同的数字,并且没有一个元素是0(元素是由函数random(70)
生成的),所以我想知道如何删除零并确保没有两个同样的数字?
您可以使用以下
const size_t N = 5;
int a[N][N];
std::srand( ( unsigned int )std::time( 0 ) );
int *p = reinterpret_cast<int *>( a );
for ( size_t i = 0; i < N * N; i++ )
{
int x;
while ( !( x = std::rand() % 70 ) || std::find( p, p + i, x ) != p + i ) {}
p[i] = x;
}
以下是的示例
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
int main()
{
const size_t N = 5;
int a[N][N];
std::srand( ( unsigned int )std::time( 0 ) );
int *p = reinterpret_cast<int *>( a );
for ( size_t i = 0; i < N * N; i++ )
{
int x;
while ( !( x = std::rand() % 70 ) || std::find( p, p + i, x ) != p + i );
p[i] = x;
}
for ( const auto &row : a )
{
for ( int x : row ) std::cout << x << ' ';
std::cout << std::endl;
}
return 0;
}
样本输出为
66 23 32 6 18
8 31 55 10 43
39 2 28 4 56
5 58 47 46 68
59 25 26 9 50
这种方法不需要额外的内存。
另一种方法是使用CCD_ 3。例如
const size_t N = 5;
int a[N][N];
std::bitset<70> b;
b.set( 0 );
std::srand( ( unsigned int )std::time( 0 ) );
for ( size_t i = 0; i < N; i++ )
{
for ( size_t j = 0; j < N; j++ )
{
int x;
while ( ( x = std::rand() % 70, b[x] ) );
//or
//while ( b[x = std::rand() % 70] );
b.set( x );
a[i][j] = x;
}
}
相关文章:
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用不带参数的函数访问结构元素
- 使用函数"remove"删除重复元素
- 如何将元素添加到数组的线程安全函数?
- 如何通过 getter 函数删除矢量的元素?
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 复制包含C++所有元素的对象!(构造函数和赋值,最佳实践?
- 如何在基类指针向量的元素上应用重载的多态函数
- 这个返回元素位置的基于循环的函数有什么问题?
- 如何在 STL 函数中找到传递给谓词的元素的索引?
- 为什么用户定义的函数不按照给定的顺序对相同长度的元素进行排序?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 交换函数不是在 C++ 中交换 2D 数组的元素
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- 如何在 c++ 中将整个数组初始化为类构造函数中的单个元素
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- 使用并行参数向量调用元素向量的成员函数
- C 在双链接列表中删除元素函数
- 将类向量的两个函数返回值与其他类向量元素函数进行比较
- 访问c++中的列表元素函数