Search code examples
c++c++11iteratoruniform-initialization

Uniform initialization of iterators


I am very new to C++11 and there is a problem with iterators and uniform initialization, which I do not understand.

Consider the following example, which does not compile:

#include <iostream>
#include <vector>

int main() {

    std::vector<int> t{1, 2, 3, 4, 5};
    auto iter{t.begin()};                   

    for (; iter != t.end(); ++iter) {
        std::cout << *iter;
    }

    return 0;
}

In line 6 a vector is initialized using uniform initialization. In line 7 I try to do the same with an iterator. It does not work. Changing line 7 to auto iter = t.begin() is ok. I know I could simply use "range based for" for this, but the question is: Why does uniform initialization not work with iterators but is fine with basic types, like int i{0}; ?


Solution

  • When you use an initializer-list as the initializer with auto, the variable declared is deduced as an initializer list. In other words, iter is declared as std::initializer_list<vector<int>::iterator>, and not vector<int>::iterator as you might expect.

    Changing it to auto iter = t.begin() is the best way to proceed.