C++ Vector string for-loop push_back error
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...
stri开发者_如何学Pythonng 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;
}
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.
string anonlist[] = {"test1","test2","test3","test4","test5","test6","test7"};
vector<string> nameurl;
for (int i=0; i < 7; i++)
{
nameurl.push_back("http://api.twitter.com/1/users/show.json?screen_name="+anonlist[i]);
cout << nameurl[i] << endl;
}
You create a new vector<string>
each time through the loop, insert a single element, then attempt to access the element at index i
. There will only be an element at index i
the first time through the loop, when i
is 0
.
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.
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.
Another way to do Ben's answer:
const string anonlist[] = {"test1", "test2", "test3", "test4", "test5", "test6", "test7"};
vector<string> nameurl(sizeof(anonlist) / sizeof(anonlist[0]), "http://api.twitter.com/1/users/show.json?screen_name=");
for (size_t i = 0; i < nameurl.size(); ++i) {
cout << (nameurl[i] += anonlist[i]) << endl;
}
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.
精彩评论