2016-11-26 2 views
0

Я пытаюсь присоединиться к простым спискам символов вместе по одному элементу за раз, чтобы создать новый список. Например, если listA = 1,2,3,4,5 и listB = a, b, c, d, e, f, listC = a, 1, b, 2, c, 3 и т. Д.Как увеличить итератор внутри тела for цикла C++

I have a function taking in two char list, but I'm not able to increment the iterators from list A and B without receiving a compiler error. 

My code is as follows: 

void altFusion(std::list<char> listOne, std::list<char> listTwo) { 
    std::list<char>::iterator iter; 
    std::list<char>::iterator nextIter; 

    iter = listOne.begin(); 
    nextIter = listTwo.begin(); 
    std::list<char>newList; 


    char temp = *iter; 
    char temp2 = *nextIter; 



    for (int i = 0; i < 10; i++) { 
     newList.push_back(temp); 
     newList.push_back(temp2); 
     ++iter; 
     ++nextIter; 

    } 

    std::list<char>::iterator newListIter; 
    for (newListIter = newList.begin(); newListIter != newList.end(); ++newListIter) { 
     std::cout << *newListIter; 
    } 
} 

Если мне не разрешено увеличивать мой итератор внутри тела цикла for, как я должен?

Если я удаляю ++ iter и ++ nextIter, программа работает, но ответ нежелателен. (a, 1, a, 1, a, 1, a, 1 ...)

Благодарим за помощь!

ответ

0
#include <iostream> 
#include <vector> 
#include <list> 
#include <iterator> 

using namespace std; 
std::list<char> listA = {'1','2','3','4','5'}; 
std::list<char> listB = {'a','b','c','d','e'}; 
     //listC = a,1,b,2,c,3 etc... 
int main() 
{ 

    std::list<char> new_list; 

    for (auto iterator = listA.begin(), end = listA.end(); iterator != end; ++iterator) 
    { 
     // get current index 
     int index = std::distance(listA.begin(), iterator); 
     // insert item from list a 
     new_list.push_back(*iterator); 

     // listb item 
     auto it = listB.begin(); 
     std::advance(it, index); 

     new_list.push_back(*it); 

    } 

    for (auto n : new_list) 
    { 
     std::cout << n << std::endl; 
    } 
    return 0; 
} 

Причина, по которой ваш приращение и предварительный приращение не работают из-за этого. вы просто используете одно и то же значение снова и снова. вы не заменяете temp и temp2.

newList.push_back(temp); 
newList.push_back(temp2); 
+0

Я вижу, как вы увеличиваете свой список с помощью std :: advance(), есть ли причина, по которой вы используете это, и почему использование pre и post (++) не работает? Является ли это проблемой? Я еще не пробовал ваше решение. –

+0

std :: advance просто увеличивает итератор на n элементов. если он отрицательный, он уменьшается. –

+0

ваш код теперь работает из-за этого.newList.push_back (temp); newList.push_back (temp2); –

Смежные вопросы