相关疑难解决方法(0)

为什么要使用strncpy而不是strcpy?

编辑:我添加了示例的源代码.

我遇到了这个例子:

char source[MAX] = "123456789";
char source1[MAX] = "123456789";
char destination[MAX] = "abcdefg";
char destination1[MAX] = "abcdefg";
char *return_string;
int index = 5;

/* This is how strcpy works */
printf("destination is originally = '%s'\n", destination);
return_string = strcpy(destination, source);
printf("after strcpy, dest becomes '%s'\n\n", destination);

/* This is how strncpy works */
printf( "destination1 is originally = '%s'\n", destination1 );
return_string = strncpy( destination1, source1, index );
printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
Run Code Online (Sandbox Code Playgroud)

哪个产生了这个输出: …

c buffer-overflow c89 strcpy strncpy

77
推荐指数
5
解决办法
17万
查看次数

PHP查找所有(某种程度上)数组的唯一组合

我整天都在看PHP数组排列/组合问题..但仍然无法弄明白:/

如果我有一个像这样的数组:

20 //key being 0    
20 //key being 1    
22 //key being 2    
24 //key being 3
Run Code Online (Sandbox Code Playgroud)

我需要组合如:

20, 20, 22 //keys being 0 1 2    
20, 20, 24 //keys being 0 1 3    
20, 22, 24 //keys being 0 2 3
20, 22, 24 //keys being 1 2 3
Run Code Online (Sandbox Code Playgroud)

我目前的代码给了我:

20, 22, 24
Run Code Online (Sandbox Code Playgroud)

因为它不想重复20 ...但这就是我需要的!

这是我的代码.它直接来自Php递归以获得字符串的所有可能性

function getCombinations($base,$n){

$baselen = count($base);
if($baselen == 0){
    return;
}
    if($n == 1){
        $return = array();
        foreach($base as $b){
            $return[] = …
Run Code Online (Sandbox Code Playgroud)

php algorithm recursion combinations permutation

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

独特的置换生成器?

问题:我有一些数字列表,例如[1,1,2]. 我需要生成唯一的排列。排列是[1,1,2],[1,1,2],[1,2,1],[1,2,1],[2,1,1],[2,1,1]。我只需要生成唯一的排列,即[1,1,2],[1,2,1],[2,1,1].

我的尝试:我的第一次尝试是保留一组现有的排列,并为itertools.permutations生成器创建一个过滤器,该过滤器将使用该组过滤掉重复项。但是,出于效率原因,我宁愿不首先生成这些排列。即使对于 12 个数字的小列表,也只有 1% 是唯一的。

我有一个我似乎无法完全弄清楚的想法的开始:我可以在我的列表中创建唯一值的排列,即[1,2],将剩余的数字放在所有不同的地方。

感谢您的帮助,并且要明确的是,我不想过滤掉重复的排列,我只想首先生成唯一的排列。

python algorithm permutation

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

获取所有不重复的组合

给出 C++ 中没有重复的字符串的所有可能组合。输入示例:“123”,输出组合为:

 1,12,123,13,2,23,3.
Run Code Online (Sandbox Code Playgroud)

重复的示例为“12”==“21”或“123”==“213”。

假设一个字符不会被多次使用。我也不认为递归是强制性的。

这里有一个 php 答案。(获取所有可能的组合而不重复)。

我考虑过某种形式的结果树,但不确定如何用递归来实现。

我的答案(包括重复项)如下:

#include <string>
#include <iostream>
using namespace std;

void get( string str, string res ) {

   cout << res << endl;

   for( int i = 0; i < str.length(); i++ )
      get( string(str).erase(i,1), res + str[i] );
}

int main( int argc, char **argv) {
   string str = "123";
   get( str, "" );
   return 0;
}
Run Code Online (Sandbox Code Playgroud)

这是一个面试问题,没有重复的问题让我很困惑。预先感谢您的任何帮助。

c++ recursion combinations

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