开发者

Error in iterator declaration in a for loop

void catchlabel()
{
    if(vecs开发者_开发技巧.empty())
        return;
    else
    {
    cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
    cout << "Currently Stored Labels: " << endl;
    /* Error 1 */
for ( int i = 1, vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it , i++) 
             cout << i << ". "<< *it << endl;
            cout << endl;
    }
}

I get the following error for:

1> error C2146: syntax error : missing ',' before identifier 'it'

How to fix this?


You can't declare items of multiple types in the initial statement of a for loop, just like you can't say int i = 1, vector<string>::iterator it = vecs.begin(); as a standalone statement. You'll have to declare one of them outside the loop.

Since the C language you have never been able to declare multiple variables of different types in one statement (although pointers are a rather odd exception):

int i, double d;  /* Invalid */

int i, j; /* Valid */

This behavior is inherited by C++, and applies to each statement within a for loop as well as standalone statements.


You can't declare variables of two different types in the "init" part of the for loop. Move the declaration of "i" (or of "it") to outside the loop.


You can use nice trick to not let your iterator out of scope:

void catchlabel()
{
    if(vecs.empty())
        return;
    else
    {
    cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
    cout << "Currently Stored Labels: " << endl;
    /* Error 1 */
    {
    vector<string>::iterator it = vecs.begin()
    for ( int i = 1; it != vecs.end(); ++it , i++) 
             cout << i << ". "<< *it << endl;
            cout << endl;
    }
    }
}

And I would say that if you need to manipulate both elements and their indexes it is simpler to use indexes in 'for' loop, not iterators.


Your for loop is wrong. You cannot declare variables of different type in the initialization part of for!

Do this:

int i = 1; 
for (vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it , i++) 
{
      cout << i << ". "<< *it << endl;
}

Or maybe, you would love just this:

for (size_t i = 0 ;  i < vecs.size(); ++i ) 
{
      cout << (i+1) << ". "<< vecs[i] << endl;
}


You don't need to count the element specifically, you can just calculate the distance from vecs.begin() as you go along:

void catchlabel()
{
    if(!vecs.empty())
    {
        cout << "The Sizeof the Vector is: " << vecs.size() << endl; 
        cout << "Currently Stored Labels: " << endl;
        for (vector<string>::iterator it = vecs.begin(); it != vecs.end(); ++it)
            cout << (it - vecs.begin() + 1) << ". "<< *it << endl; 
        cout << endl;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜