gpt4 book ai didi

c++ - 在 C++ 中使用堆栈和 vector 以相反顺序打印字符串

转载 作者:行者123 更新时间:2023-11-27 23:17:09 25 4
gpt4 key购买 nike

快速提问:我正在尝试接受一个字符串参数,然后使用堆栈和 vector 向后打印它。但是,在显示 Here you go! 后,屏幕上没有任何内容打印。我相信它与 vector 设置有关,因为我以前从未使用过它。这是有问题的代码。如果有任何帮助,我将不胜感激!

void main() {

stack<char> S;
string line;
vector<char> putThingsHere(line.begin(), line.end());
vector<char>::iterator it;

cout << "Insert a string that you want to see backwards!" << endl;
cin >> line;

for(it = putThingsHere.begin(); it != putThingsHere.end(); it++){
S.push(*it);
}

cout << "Here you go! " << endl;

while(!S.empty()) {
cout << S.top();
S.pop();
}

system("pause");


}

最佳答案

line 时,您的 vector 初始化过早还是空的。搬迁施工putThingsHere 下面从标准输入中提取字符串的指令:

cin >> line;
vector<char> putThingsHere(line.begin(), line.end());

这是一个live example您的固定程序运行正常。

注意 getline() 的使用而不是 cin >> line , 这样字符之间的空格仍然可以作为单个字符串的一部分读取。

说到这里,值得一提的是std::string满足标准序列容器的要求,特别是具有成员函数 begin()end()返回 std::string::iterator .

因此,您不需要 std::vector<>完全可以,下面的代码片段就可以完成这项工作:

getline(cin, line);
for(std::string::iterator it = line.begin(); it != line.end(); it++) {
S.push(*it);
}

关于c++ - 在 C++ 中使用堆栈和 vector 以相反顺序打印字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15689587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com