C++矢量字符串for循环push_back错误
我觉得这是理所当然的,但由于某种原因我无法理解发生了什么。
当我运行这部分代码时,它将 URL 与数组中的字符串元素组合在一起,然后将其推送到字符串向量中,它成功推送了第一个 URL,但随后出现了某种内存泄漏?控制台无限循环乱码......
string anonlist[] = {"test1","test2","test3","test4","test5","test6","test7"};
for (int i=0; i<=7; i++)
{
vector<string> nameurl;
nameurl.push_back("http://api.twitter.com/1/users/show.json?screen_name="+anonlist[i]);
cout << nameurl[i] << endl;
}
I feel like this is a no-brainer, but for some reason I can't understand what's happening.
When I run this part of my code, which is combining a URL with string elements from an array and then pushing that into a string vector, it pushes the first URL successfully, but then has some sort of memory leak afterwards? The console infinitely loops gibberish...
string anonlist[] = {"test1","test2","test3","test4","test5","test6","test7"};
for (int i=0; i<=7; i++)
{
vector<string> nameurl;
nameurl.push_back("http://api.twitter.com/1/users/show.json?screen_name="+anonlist[i]);
cout << nameurl[i] << endl;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
数组中有 7 个项目,索引为 0 1 2 3 4 5 6。您的循环还将包括 i = 7 的情况,该情况超出了数组的范围。
另一个问题是您在循环内部声明向量,这意味着每次循环继续时都会创建一个新向量。您应该在循环之前声明它。
There are 7 items in the array indexed 0 1 2 3 4 5 6. Your loop will also include the case where i = 7 which is out of the bounds of the array.
Another issue is that you declare the vector inside of the loop, which means that every time the loop continues a new vector is created. You should declare it before the loop.
每次循环时都会创建一个新的
vector
,插入一个元素,然后尝试访问索引i
处的元素。当i
为0
时,第一次循环时索引i
处只会有一个元素。大概您希望将
nameurl
的声明移到循环之外,以便同一容器用于循环的所有迭代。You create a new
vector<string>
each time through the loop, insert a single element, then attempt to access the element at indexi
. There will only be an element at indexi
the first time through the loop, wheni
is0
.Presumably you want to move the declaration of
nameurl
outside of the loop so that the same container is used for all the iterations of the loop.每次通过 for 循环都会创建一个新向量——该向量仅在 for 循环内具有块作用域。您应该将向量移到循环之外。
You are creating a new vector every time through the for-loop -- this vector only has block scope inside the for loop. You should move the vector outside the loop.
本回答的另一种方法是:
这样,您可以只编辑非列表,而无需触及其余代码。并且,它构造了一个向量,其中所有元素都设置为基本 URI,这很好。
Another way to do Ben's answer:
That way, you can just edit anonlist without touching the rest of the code. And, it constructs the vector with all the elements set to the base URI, which is kind of nice.