C++ 从 std::string 数组创建 std::vector

C++ creating a std::vector from std::string array

我正在学习 C++,并且正在学习一门课程。最后一个练习涉及为一副纸牌编写一个程序。我想到了一个办法:

我最初尝试用字符串数组做所有事情,但后来意识到使用向量会更有意义。我现在正尝试从我的 std::string 数组中创建一个 std::vector std::string,但没有成功。

我在网上找到了一些示例代码,例如: 来自 https://thispointer.com/5-different-ways-to-initialize-a-vector-in-c/

并尝试为我的程序实现它,但是,我无法让它工作,也无法完全理解问题所在。

我的代码:


#include <iostream>
#include <string>
#include <vector>




class card_deck {
public:
    card_deck();
    std::vector<std::string> deal_hand(int num_cards);
    void new_deck();
    

private:
    //std::vector<std::string> cards_vector;
    std::string cards[52] =
    {
        "As","2s","3s","4s","5s","6s","7s","8s","9s","Ts","Js","Qs","Ks",
        "Ah","2h","3h","4h","5h","6h","7h","8h","9h","Th","Jh","Qh","Kh",
        "Ad","2d","3d","4d","5d","6d","7d","8d","9d","Td","Jd","Qd","Kd",
        "Ac","2c","3c","4c","5c","6c","7c","8c","9c","Tc","Jc","Qc","Kc"
    };

    std::vector<std::string> cards_vector(cards, sizeof(cards)/sizeof(std::string) );
    
};

从我的代码可以看出,我在我的私有变量中初始化了一个字符串数组,然后想把这个字符串数组转换成std::vector

返回的错误信息:

更新

代码在 main() 中调用时有效

int main()
{
    std::string cards[52] =
    {
        "As","2s","3s","4s","5s","6s","7s","8s","9s","Ts","Js","Qs","Ks",
        "Ah","2h","3h","4h","5h","6h","7h","8h","9h","Th","Jh","Qh","Kh",
        "Ad","2d","3d","4d","5d","6d","7d","8d","9d","Td","Jd","Qd","Kd",
        "Ac","2c","3c","4c","5c","6c","7c","8c","9c","Tc","Jc","Qc","Kc"
    };

    // Initialize vector with a string array
    std::vector<std::string> vecOfStr(cards, cards + sizeof(cards) / sizeof(std::string));
    for (std::string str : vecOfStr)
        std::cout << str << std::endl;

}

在class

中使用时不起作用
#include <iostream>
#include <string>
#include <vector>

class card_deck {
public:
    card_deck();
    std::vector<std::string> deal_hand(int num_cards);
    void new_deck();
    

private:

    std::string cards[52] =
    {
        "As","2s","3s","4s","5s","6s","7s","8s","9s","Ts","Js","Qs","Ks",
        "Ah","2h","3h","4h","5h","6h","7h","8h","9h","Th","Jh","Qh","Kh",
        "Ad","2d","3d","4d","5d","6d","7d","8d","9d","Td","Jd","Qd","Kd",
        "Ac","2c","3c","4c","5c","6c","7c","8c","9c","Tc","Jc","Qc","Kc"
    };

    // Initialize vector with a string array
    std::vector<std::string> vecOfStr(cards, cards + sizeof(cards) / sizeof(std::string));
    for (std::string str : vecOfStr)
        std::cout << str << std::endl;
    
};



int main()
{

}

简单方法:

std::vector<std::string> cards {
    "As","2s","3s","4s","5s","6s","7s","8s","9s","Ts","Js","Qs","Ks",
    "Ah","2h","3h","4h","5h","6h","7h","8h","9h","Th","Jh","Qh","Kh",
    "Ad","2d","3d","4d","5d","6d","7d","8d","9d","Td","Jd","Qd","Kd",
    "Ac","2c","3c","4c","5c","6c","7c","8c","9c","Tc","Jc","Qc","Kc"
};

并删除单独的 cards_vector 成员。 cards.size() 产生向量中的元素数。

这使用了 C++11 的初始化列表语法。

并且编译器会为您计算出大小:例如,如果您以后需要添加小丑,这会很方便。