Iterator question...

B

barcaroller

Can anyone tell me why the first block of code fails to compile, while the
second works fine.


Block 1
=======

vector<int> myvector;
string mystr;

void foo( vector<int>::const_iterator begin,
vector<int>::const_iterator end )
{
myvector.assign(begin, end);
}

//
// Compiler error; string iterators not accepted as vector iterators
//
foo(mystr.begin(), mystr.end());


gcc output
-----------
error: conversion from '__gnu_cxx::__normal_iterator,
std::allocator > >' to non-scalar type
'__gnu_cxx::__normal_iterator > >' requested


Block 2
=======

//
// But this works; string iterators accepted as vector iterators
//
myvector.assign(mystr.begin(), mystr.end());
 
A

Andrey Tarasevich

barcaroller said:
Block 1
=======

vector<int> myvector;
string mystr;

void foo( vector<int>::const_iterator begin,
vector<int>::const_iterator end )
{
myvector.assign(begin, end);
}

//
// Compiler error; string iterators not accepted as vector iterators
//
foo(mystr.begin(), mystr.end());

The compiler error says it all.
Block 2
=======

//
// But this works; string iterators accepted as vector iterators
//
myvector.assign(mystr.begin(), mystr.end());

No, they are not accepted as vector iterators. They are accepted as
_string_ iterators. Note that 'vector<>::assign' is a template method.
When you call it with string iterators as parameters, a dedicated
version for string iterators is instantiated.

The same thing with an intermediate 'foo' function would look as follows

void foo(string::iterator begin, string::iterator end)
{
myvector.assign(begin, end);
}

...

foo(mystr.begin(), mystr.end());

which is what you apparently tried to do in your "Block 1", but for some
reason you used vector iterators as parameters.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,999
Messages
2,570,246
Members
46,840
Latest member
BrendanG78

Latest Threads

Top