【发布时间】:2021-08-13 16:52:14
【问题描述】:
我正在学习 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;
}
在课堂上使用时不起作用
#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()
{
}
【问题讨论】:
-
请勿以图片形式发布编译器错误消息,而应以逐字代码格式的文本形式发布。还要删除与重现问题无关的任何内容,您将在描述minimal reproducible example 的文章中找到指导。欢迎您的合作。
-
sizeof(cards)-- 请打印这个值是什么。你可能会感到惊讶。 (不是 52)。 -
std::vector<std::string> cards_vector(cards, cards + sizeof(cards));-- 尽管此行不是必需的,但您没有按照您发布的链接中的说明进行操作。从数组初始化向量需要cards + sizeof(cards) / sizeof(std::string)。这就是最初发表评论的原因。 -
我现在看到了。但是,仍然返回相同的错误。我已经编辑了我的初始代码。我不确定它为什么抱怨
member "card_deck::cards" is not a type name. -
您的“在课堂上使用时不起作用”sn-p 无法编译。语句必须在函数中。
标签: c++ arrays string vector std