【问题标题】:iterator header: can't use begin or end with array as argument, c++11迭代器标头:不能使用数组作为参数的开始或结束,c++11
【发布时间】:2014-02-28 21:12:08
【问题描述】:

1>c:\users\indira\documents\visual studio 2012\projects\cpppremier\cpppremier\ch1.cpp(2060): error C3861: 'begin': identifier not found

1>c:\users\indira\documents\visual studio 2012\projects\cpppremier\cpppremier\ch1.cpp(2060): error C3861: 'end': identifier not found

========== 构建:0 成功,1 失败,0 最新,0 跳过 ==========

#include <iostream>
#include <string>
#include <cstddef>
#include<array>
#include<vector>
#include <iterator>
using std::string;
using std::cin;
using std::cout;
using std::endl;

int main()
{

    int ia[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    int *pbeg = begin(ia),  *pend = end(ia);

    cout << "Elements in arr: " << endl;

   for (int *pbeg; pbeg != pend; ++pbeg)
    { 
        *pbeg = 0;
        cout << *pbeg << endl;
    }


    getchar();
    getchar();

return 0;
}

我不明白为什么这不起作用。我正在尝试使用迭代器标头来使用该标头中定义的开始和结束函数。 该代码具有迭代器标头。这些函数将数组作为参数,因为数组不是类类型...... 我在 Visual Studio 2013 和 compileonline.com c++11 中尝试过。

【问题讨论】:

    标签: arrays pointers iterator


    【解决方案1】:

    beginendstd 命名空间中的函数,所以你应该用using 来引入它们,或者限定它们(例如std::begin)。

    当你的参数本身是 std 类型时,你不需要这个:在这种情况下,依赖于参数的查找会找到它们 - 但是当你的参数是原始类型或其他任何没有在内部定义的东西时,ADL 不起作用namespace std.


    这里有一些示例代码来解释在这种情况下名称查找是如何工作的。仅仅因为某些内容在翻译单元中可见,并不意味着它是有效的匹配。

    namespace test {
        struct Type { };
    
        void foo(Type);
        void bar(int);
    }
    
    int main() {
        /*
        Type t; <-- NO: Type is declared but not visible for name lookup
            nl.cpp: In function ‘int main()’:
            nl.cpp:11:5: error: ‘Type’ was not declared in this scope
            nl.cpp:11:5: note: suggested alternative:
            nl.cpp:3:12: note:   ‘test::Type’
        */
    
        test::Type u; // OK: the qualified name can be looked up
        foo(u);       // OK: argument-dependent lookup means test is considered
    
        /*
        bar(1); <--  NO: int isn't part of namespace test
            nl.cpp:22:10: error: ‘bar’ was not declared in this scope
            nl.cpp:22:10: note: suggested alternative:
            nl.cpp:6:10: note:   ‘test::bar’
        */
    
        test::bar(1); // OK: explicitly tell the compiler where to look
    }
    

    您可以使用 using 将来自不同名称空间的名称引入当前名称(您已经使用 std::string 等),或者明确限定它们。

    【讨论】:

    • 开始和结束函数在迭代器头中定义。它应该在没有 std::begin 的情况下工作。如果我将代码更改为仍然无法正常工作: int *pbeg = std::begin(ia) 是“未初始化使用”。
    • 它们在std命名空间的头文件中定义。请注意,随着您的更改,您会遇到 different 错误,我怀疑它在 for 循环中,您在其中声明了一个新的、未初始化的 pbeg 变量,它隐藏了现有的变量。
    • 通过纠正未初始化的问题,代码可以工作(使用你的建议我也可以删除#include,原因是从std命名空间访问它。)。但我仍然不明白为什么迭代器标头不起作用。这是一个链接,它显示这些函数是在此标头中定义的。所以最初的问题仍然困扰着我:使用迭代器标头。msdn.microsoft.com/en-us/library/k3tf6509.aspx
    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 1970-01-01
    相关资源
    最近更新 更多