简体   繁体   English

返回指针的函数的打印数组

[英]Print array of a function that return a pointer

Hello I try do a function that can split every text I want. 您好,我尝试做一个可以分割我想要的每个文本的函数。 For example if I enter apple::google::dsf and the delimitor is :: every element will be put in a place in an array. 例如,如果我输入apple :: google :: dsf且分隔符为::,则每个元素都将放置在数组中的某个位置。 I success to do this, but now I want to be able to use this array in my main. 我成功地做到了这一点,但是现在我希望能够在我的主体中使用此阵列。 So I want to print the array that I return in my function in the main and not to print the array from the function Split(). 所以我想打印在主函数中返回的数组,而不是从功能Split()打印数组。 So my question is how to do this ? 所以我的问题是如何做到这一点? This is my code : 这是我的代码:

int main()
{
    string buffer; string delimitor = "::";
    unsigned int param = 0;
    cout << "Please enter how many param: "; cin >> param;
    cout << "Please enter something in the buffer: "; cin >> buffer;
    Split(buffer, delimitor, param);

    system("PAUSE");
    return 0;
}

string* Split(string buffer, string delimitor, unsigned int nbr_param)
{
    string* arr = new string[nbr_param];
    unsigned int start = 0, end = buffer.find(delimitor), count = 0;
    while (end != string::npos)
    {
        arr[count] = buffer.substr(start, end - start);
        start = end + delimitor.length();
        end = buffer.find(delimitor, start);
        count++;
    }
    if (end == string::npos)
    {
        arr[count] = buffer.substr(start, end);
    }

    return arr;
}

Store return value in variable, than iterate over it. 将返回值存储在变量中,然后对其进行迭代。

std::string* words = Split(buffer, delimitor, param);
for (std::size_t i = 0; i != param; ++i) {
    std::cout << words[i] << std::endl;
}
delete[] words;

If you return std::vector<std::string> , you may do 如果返回std::vector<std::string> ,则可以这样做

const auto& words = Split(buffer, delimitor); // param is no longer needed.
for (const auto& word : words) {
    std::cout << words[i] << std::endl;
}

It would be easier to use std::vector , push_back the fragments and do away with the new altogether. 这将是更容易使用std::vectorpush_back的片段,并废除了new完全。 Probably also just as efficient, as the returned vector would be either moved or constructed in place due to the RVO. 可能也同样有效,因为返回的矢量由于RVO而被移动或构建到位。

Anyway, you will of course have to assign the return value to a variable in main. 无论如何,您当然必须将返回值分配给main中的变量。 Right now you just call split and discard the value, leaking the memory allocated in Split . 现在,您只需要调用split并丢弃该值,就可以泄漏Split分配的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM