vendredi 26 août 2016

C++ sequential container initialization using iterator

I'm trying to create sub containers of a container through container<\T>(InputIt First, InputIt Last). For example, I have a string s1="AreYouOK". The expected outputs are

A
Ar
Are
AreY
AreYo
AreYou
AreYouO

Here is my code:

#include <vector>
#include <string>
#include <iostream>

using std::vector;
using std::string;
using std::cout;
using std::cin;
using std::endl;

int main()
{
    string s1 = "AreYouOK";
    vector<string> v;

    for (string::const_iterator iter = s1.begin();
            iter != s1.end()-1; ++iter)
    {
        string s(s1.begin(),iter); // no matching container
        s += *iter;
        v.push_back(s);
    }

    for (vector<string>::const_iterator iter = v.begin();
            iter != v.end(); ++iter)
    {
        cout << *iter <<endl;
    }

    return 0;
}

I expect the commented line

string s(s1.begin(),iter);

to create a substring s of string s1 in range [s1.begin(), iter), since iter is an iterator of s1. However, I was told that there is no matching constructor for initialization.

error: no matching constructor for initialization of 'string' 
(aka 'basic_string<char, char_traits<char>, allocator<char> >')
string s(s1.begin(),iter);
       ^ ~~~~~~~~~~~~~~~

While

string s(s1.begin(),s1.begin+3); 

did manage to create a substring.

Why

string s(s1.begin(),iter);

did not work?

Many thanks!

Aucun commentaire:

Enregistrer un commentaire