Insert 4 letters at the beginning of the vector

0

I have to insert 4 letters at the beginning of the vector

#include <vector>
#include <list>
using namespace std;
int main(){
    int i;
    char c='a';
    vector <char> caracter(10);
    for(i=0;i<10;i++){
        caracter[i]=c;
        c++;
    }
    cout<<"letras del alfabeto"<<endl;
    for(i=0;i<10;i++){
        cout<<caracter[i]<<"-"; 
    }
    cout<<" "<<endl;
    //v.push_front(T)   segun un folleto que nos dio el profe sirve para insertar un elemento al principio del vector
    caracter.push_front(T);//no se como utilizarlo 
/*  for(i=0;i<4;i++){
        caracter[i]='c';
    }*/
    cout<<"4 letras c insertadas al inicio"<<endl;
    for(i=0;i<10;i++){
        cout<<caracter[i]<<"-"; 
    }
    return 0;
}
    
asked by Edwin Casco 06.04.2017 в 16:30
source

1 answer

1

According to the documentation (which you should start to familiarize yourself with) the vector key does not have of any method called push_front .

However, the documentation for the class list indicates that the container does contain such method.

The operation is very simple. list represents a list doubly linked and push_front inserts an element at the beginning of the list:

std::list<char> items;
items.push_front('a');
items.push_front('b');

// En este punto la lista contiene B -> A

Now, if the problem has to be solved with vector the thing is slightly complicated because, as we have seen, vector does not have this method.

You can choose to add the elements one by one using the insert method:

std::vector<char> lista;

// Para rellenar la lista
lista.push_back('a');
lista.push_back('b');
lista_push_back('c');

// Nuevo elemento al inicio
lista.insert(lista.begin(),'c'); // esto 4 veces

for( size_t i=0; i<lista.size(); i++ )
  std::cout << lista[i];

Or you can create a second vector and add its content to the start of your list:

std::vector<char> lista;

// Para rellenar la lista
lista.push_back('a');
lista.push_back('b');
lista_push_back('c');

// Nuevo contenedor
std::vector<char> nuevos(4,'c'); // Crea cuatro elementos con valor 'c'

// Nuevo elemento al inicio
lista.insert(lista.begin(),nuevos.begin(),nuevos.end());

for( size_t i=0; i<lista.size(); i++ )
  std::cout << lista[i];
    
answered by 06.04.2017 в 16:42