Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Iterator question...

Reply
Thread Tools

Iterator question...

 
 
barcaroller
Guest
Posts: n/a
 
      11-18-2009
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());





 
Reply With Quote
 
 
 
 
Andrey Tarasevich
Guest
Posts: n/a
 
      11-19-2009
barcaroller wrote:
> 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.

--
Best regards,
Andrey Tarasevich
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
List iterator assignment fails, assert iterator not dereferencable David Bilsby C++ 5 10-09-2007 02:05 PM
What makes an iterator an iterator? Steven D'Aprano Python 28 04-20-2007 03:34 AM
Difference between Java iterator and iterator in Gang of Four Hendrik Maryns Java 18 12-22-2005 05:14 AM
How to convert from std::list<T*>::iterator to std::list<const T*>::iterator? PengYu.UT@gmail.com C++ 6 10-30-2005 03:31 AM
Iterator doubts, Decision on Iterator usage greg C++ 6 07-17-2003 01:26 PM



Advertisments