gpt4 book ai didi

c++ - 迭代 vector 以识别段落

转载 作者:行者123 更新时间:2023-11-30 02:57:41 25 4
gpt4 key购买 nike

我现在进入了一本书(C++ Primer 5th Edition)中关于迭代器的章节。到目前为止,这看起来相当简单,但我遇到了一些小挑战。

书中的问题是“...将 text [a vector] 中与第一段相对应的元素更改为全部大写并打印其内容。”

我遇到的第一个问题是,在本书的第 110 页上,它给出了示例代码,用于识别 vector 中是否有空元素表示段落的结尾。代码如下,摘自书中:

// print each line in text up to the first blank line
for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it);
cout << *it << endl;

但是,当我在编辑器中键入此内容时,我收到一条错误消息 *it 说:使用未声明的标识符“it”。

如果我想创建一个 vector text 并从输入中读取元素,然后运行一个迭代器来检查是否有段落结尾,然后将整个段落大写并打印结果,我该怎么做?

我以为我知道,但是我一输入示例代码,就报了上面的错误。

这是我提供的代码(在进行任何大写之前我想测试它是否可以阅读一个段落)并且正在玩,但是所有这些只是打印最后输入的单词。

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

using std::string; using std::vector; using std::cout; using std::cin; using std::endl;

int main ()
{
const vector<string> text;
string words;

while (cin >> words) {
for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it);
}
cout << words << endl;
}

一如既往地感谢您的帮助!

最佳答案

您在 for 循环中声明了局部迭代器,但是您在循环之后放置了一个分号,因此行 cout << *it << endl;不是循环的一部分,变量 it不在范围内。只需删除分号就可以了:

 for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it)//no semicolon here
cout << *it << endl;

为了更好地说明发生了什么,这里有一对带括号的例子:

 //your original code:
for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it)
{

}
cout << *it << endl; //variable it does not exist after the for loop ends

//code that works:
for (auto it = text.cbegin(); it != text.cend() && !it->empty(); ++it)
{
cout << *it << endl; //what happens _unless_ you put a ; after the loop statement
}

我不知道这是否能解决您的整个问题,但它应该可以解决您遇到的错误。

关于c++ - 迭代 vector 以识别段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14331615/

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