can anyone please explain different with vector::begin() and std::begin() ??
the code is based on the book, Effective Modern C++ item13.

#include <iterator>
#include <boost/type_index.hpp>

using namespace boost::typeindex;

#define PRINT_TYPENAME(__param) do {                                    \
    std::cout << "param (" << #__param << ") "                          \
                << type_id_with_cvr<decltype(__param)>().pretty_name()  \
                << std::endl;   \
} while(0)

int main() {
    std::vector<int> v = {1, 2, 3,4, 1993, 2014};
    std::vector<int>::iterator vi = std::find(v.begin(), v.end(), 1993);
    v.insert(vi, 1998);

    auto it = std::find(v.cbegin(), v.cend(), 1993);
    PRINT_TYPENAME(it);
    // param (it) __gnu_cxx::__normal_iterator<int const*, std::vector<int, std::allocator<int> > >
    //v.insert(it, 1998); // compile error : no matching member function for call to 'insert'  

    auto it2 = std::find(std::begin(v), std::end(v), 1993);
    PRINT_TYPENAME(it2);
    // param (it2) __gnu_cxx::__normal_iterator<int*, std::vector<int, std::allocator<int> > >
    v.insert(it2, 1998); // compile ok

    return 0;
}

Recommended Answers

All 2 Replies

std::begin is simply templated to use the container's begin, so there should be no difference.

On line 20 you're trying to use a const iterator to change a value.

compile error : no matching member function for call to 'insert'

There is no error in the posted code (once the missing headers are added).
Since C++11, insert() and erase() on standard constainers accept const_iterators.
http://en.cppreference.com/w/cpp/container/vector/insert
http://en.cppreference.com/w/cpp/container/vector/erase

Note: this does not break legacy code. The IS requires that for a standard container, there must be an implicit converstion from iterator to const_iterator.

You appear to be using an old version of libstdc++ which is still in legacy mode wrt this.

LLVM and GNU: http://coliru.stacked-crooked.com/a/51d6e6b2a90106fc

Microsoft: http://rextester.com/JRJP63287

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.