在 C++ 中返回字符串数组

Posted

技术标签:

【中文标题】在 C++ 中返回字符串数组【英文标题】:return string arrays in c++ 【发布时间】:2018-10-05 23:00:51 【问题描述】:

我是 c++ 新手,在尝试开发 go 之后,我想不妨学习 c++,因为当我开始深入抽象层时,学习曲线会非常陡峭,我习惯于在 php 中轻松处理动态数组我无法理解与 c++ 相关的指针、内存分配和范围问题,这是我的第一次尝试:

string* Deck() 
    // array of card rank and vlaue, seperated by a period, used as a delimiter for evaluting the players hands
    string* Deck = new string[52] ;
    Deck = 
        "A.H","2.H","3.H","4.H","5.H","6.H","7.H","8.H","9.H","10.H","J.H","Q.H","K.H",
        "A.S","2.S","3.S","4.S","5.S","6.S","7.S","8.S","9.S","10.S","J.S","Q.S","K.S",
        "A.D","2.D","3.D","4.D","5.D","6.D","7.D","8.D","9.D","10.D","J.D","Q.D","K.D",
        "A.C","2.C","3.C","4.C","5.C","6.C","7.C","8.C","9.C","10.C","J.C","Q.C","K.C",
    ;

    return Deck;


int main()

    string* Deck = Deck();
    cout << *Deck[23] << endl;
    return 0;

编译器给了我各种错误,我尝试简单地返回指针,但我在这篇文章中发现了范围Return string array in C++ function

有很多关于 int 作为数据类型的文章,但 stringsint=&gt;string 的解释很少见,因为我猜每个人都认为即使是菜鸟也能弄清楚,但我已经观看了无数小时的 youtube 视频,但仍然不能想办法 。谢谢。

【问题讨论】:

“我已经观看了无数小时的 youtube 视频”——这就是你出错的地方;你需要阅读一本好的 C++ 教科书。 “编译器给了我各种错误” - 你能发布一个错误,我们可以尝试帮助你解决它吗?我以前从未使用过 std::strings 数组,但我猜你只想要 cout &lt;&lt; Deck[23] &lt;&lt; endl; 没有星号:这会给 cout 一个 std::string ,我认为它可以在没有任何进一步转换的情况下打印。 (我假设您并不是要取消引用指针以获取仅打印的第一个字符,如果这是一个 C 而不是 C++ 字符串的数组,会发生这种情况?) ideone.com/e8DvzS 这段代码中的错误太多了。人们不只是对你直言不讳。你真的真的需要拿到一本书。你需要先掌握语言;然后您可以提出具体问题。 我也怀疑调用所有东西Deck - 特别是同时具有变量和函数调用相同的东西。即使它按原样工作(我不确定它会不会),如果你给它们起不同的名字,读者会更清楚哪个 Deck 是哪个。 【参考方案1】:

" 我习惯于在 php 中轻松处理动态数组,但是我无法理解与 c++ 相关的指针、内存分配和范围问题"

在处理动态数组时,您无需像在PHP 中那样处理C++ 中的“指针、内存分配和范围问题”。 p>

只需使用std::vector,它会为您管理数组:

std::vector<std::string> GetDeck() 

    // array of card rank and vlaue, seperated by a period, used as a delimiter for evaluting the players hands
    std::vector<std::string> Deck =
    
        "A.H","2.H","3.H","4.H","5.H","6.H","7.H","8.H","9.H","10.H","J.H","Q.H","K.H",
        "A.S","2.S","3.S","4.S","5.S","6.S","7.S","8.S","9.S","10.S","J.S","Q.S","K.S",
        "A.D","2.D","3.D","4.D","5.D","6.D","7.D","8.D","9.D","10.D","J.D","Q.D","K.D",
        "A.C","2.C","3.C","4.C","5.C","6.C","7.C","8.C","9.C","10.C","J.C","Q.C","K.C",
    ;

    return Deck;


int main()

    auto Deck = GetDeck();
    std::cout << Deck[23] << '\n';

【讨论】:

我支持这个。如果您看到任何鼓励您使用原始指针或上帝禁止手动内存管理的教程(原始new \ delete)知道这不是 C++ 应该使用的方式。

以上是关于在 C++ 中返回字符串数组的主要内容,如果未能解决你的问题,请参考以下文章

C ++:从函数、返回类型或引用中使用和返回字符数组?

C++ 函数返回一个向量/字符串,但不是一个数组

C++ 数组与字符串⁽²³⁾|函数与数组

C++ 怎么编写一个字符串中某个字符出现n次的所有位置,返回值为指针数组,

将 C++ 中的数组转换为字符串

C++怎么把string 转换为char型数组