如何将char *从char **传递给const char *

时间:2017-04-21 03:09:52

标签: c++

#include "stdafx.h"
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int len = 10;
char * strNumber1 = new char[2*len+1];
char * strNumber2 = new char[2*len+1];
int cmp(const char *str1,const char *str2){
    strcpy(strNumber1,*(const char**)str1);
    strcat(strNumber1,*(const char**)str2);

    strcpy(strNumber2,*(const char**)str2);
    strcat(strNumber2,*(const char**)str1);

    return strcmp(strNumber1,strNumber2);
}
string PrintMinNumber(vector<int> numbers) {
    int length = numbers.size();

    char **numStr = new char*[10];
    for(int i = 0; i < length; i++){
        sprintf(numStr[i],"%d",numbers[i]);
    }

    sort((char*) numStr[0],(char*)numStr[length],cmp);
    // I don't know how to pass the char* from char** numStr;
    string ans = "";
    for(int i = 0; i < length; i++){
        ans += numStr[i];
    }
    return ans;
}
int _tmain(int argc, _TCHAR* argv[])
{
    int a[3] = {3,32,321};
    vector<int> numbers(a,a+3);
    cout<<PrintMinNumber(numbers);
    return 0;
}

以上是我的代码,用于解决问题,即如何从3,321,32获得最小数量。我们可能得到的结果是321323.所以我需要对字符串进行排序,但我不知道如何将char *char**传递给const char*。你能解释一下我需要做什么吗?

1 个答案:

答案 0 :(得分:0)

这个改进的解释:

如果您初始化:char **numStr = new char*[10];
实际上你已经有10个char *类型的数组。

你可以这样想象:
numStr = [addressOfChar-0,addressOfChar-1,...,addressOfChar-9];
然后对于sort函数,可以直接填充Y的begin-index和end-index参数,如下所示:
sort(numStr,numStr + length,cmp);

对于函数cmp(int cmp(const char *str1,const char *str2))中strcpy和strcat的参数,您不需要强制转换为(const char **)。因为str1和str2是numStr或addressOfChar-N的元素。

对于strcmp,你必须比较小于0,因为如果返回-1结果为真,你可以尝试下面的代码:
bool check = (-1? True: false);

您不要忘记使用内存堆(delete)的所有变量new,因为它可能会导致内存泄漏。

#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
int len = 10;
char * strNumber1 = new char[2*len+1];
char * strNumber2 = new char[2*len+1];
int cmp(const char *str1,const char *str2){
    strcpy(strNumber1,str1);
    strcat(strNumber1,str2);

    strcpy(strNumber2,str2);
    strcat(strNumber2,str1);
    return strcmp(strNumber1, strNumber2) < 0;
}
string PrintMinNumber(vector<int> numbers) {
    int length = numbers.size();
    char **numStr = new char*[10];
    for(int i = 0; i < length; i++){
        if (numbers[i] == 0)
        {
            numStr[i] = new char[2];
        }
        else
        {
            numStr[i] = new char[log(numbers[i]) + 2];
        }

        sprintf(numStr[i],"%d",numbers[i]);
    }

    sort(numStr,numStr + length,cmp);
    string ans = "";
    for(int i = 0; i < length; i++){
        ans += numStr[i];
        delete[] numStr[i];
    }
    delete[] numStr;
    return ans;
}
int main()
{
    int a[] = { 321,3,32 };
    vector<int> numbers(a,end(a));
    cout<<PrintMinNumber(numbers);
    delete[] strNumber1;
    delete[] strNumber2;
    return 0;
}