简体   繁体   English

C++11 基于指针向量的范围

[英]C++11 range-based for on a vector of pointers

I have just compiled GCC 4.6.0, and I wanted to try the new features out, starting with the range-based for loop.我刚刚编译了 GCC 4.6.0,我想尝试新功能,从基于范围的 for 循环开始。
The first loop I wanted to change was iterating on a std::vector of pointers.我想改变的第一个循环是在指针的 std::vector 上迭代。 I changed the code to use the new syntax, but it didn't compile.我更改了代码以使用新语法,但它没有编译。

I have tried to substitute another for loop, which was on a std::vector of structs, and it compiled and ran perfectly.我试图替换另一个 for 循环,它位于结构的 std::vector 上,并且它编译并运行得很好。

Here is a short test code to show you my problem:这是一个简短的测试代码,向您展示我的问题:

#include <vector>
#include <iostream>

int main()
{
    std::vector< int > values;
    
    values.push_back(2);
    values.push_back(5);
    values.push_back(8);
    values.push_back(13);
    values.push_back(17);
    
    for (int &n : values)
    {
        std::cout << n << "\n";
    }
    
    std::vector< int* > pointers;
    
    pointers.push_back(new int(2));
    pointers.push_back(new int(5));
    pointers.push_back(new int(8));
    pointers.push_back(new int(13));
    pointers.push_back(new int(17));
    
    for ((int*) &p : values)
    {
        std::cout << (*p) << "\n";
    }
    
    for( unsigned int i = 0; i < pointers.size(); ++i)
    {
        delete pointers[i];
    }
    
    return 0;
}

When I try to compile it (yes, I give -std=c++0x as a parameter to g++) , it dies with this error:当我尝试编译它时(是的,我将 -std=c++0x 作为参数提供给 g++) ,它会因以下错误而死:

main.cpp|27|error: found ':' in nested-name-specifier, expected '::' main.cpp|27|错误:在嵌套名称说明符中找到“:”,应为“::”

If I comment the lines 27-30 out, it's OK.如果我将第 27-30 行注释掉,就可以了。

What am I doing wrong?我究竟做错了什么? Isn't the pointer-reference declaring syntax right?指针引用声明语法不对吗?
Or is there a limitation of contained types where range-based for loops can be used?或者是否存在可以使用基于范围的 for 循环的包含类型的限制?

for ((int*) &p : values)

This is wrong.这是错误的。 (int*) is an expression alone, so you need to do int*& (with no parenthesis, that makes an expression - aka "not a type name") at least to make it correct. (int*)是一个单独的表达式,所以你需要做int*& (没有括号,这使得表达式 - 又名“不是类型名称”)至少使其正确。 I prefer to use auto or auto&, personally.我个人更喜欢使用 auto 或 auto&。

You can do :你可以做 :

for (auto p : values) // here p is a pointer, a copy of each pointer

or或者

for (auto& p : values ) // here p is a non-const reference to a pointer

or或者

for ( int* p : values ) // here p is a copy of each pointer

or in generic code:或在通用代码中:

for ( auto&& p: values ) // p is either a const reference to what is in values, or a non-const reference, depends on the context

我认为您打算在那里迭代“指针”而不是“值”...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM