将列表元素插入向量,获取其他不需要的值C ++

时间:2016-02-17 21:17:28

标签: c++ list vector insert

在我的C ++脚本中,我想将列表的一些元素插入到一个向量中(从列表的开头到特定位置"它"),然后尝试在顶部添加向量列表和保持相同的矢量顺序,但我在矢量中得到了不需要的额外元素。

这是我的代码:

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

int main() {

std::list<int> mylist;

for (int i = 0; i < 10; i++)
    mylist.push_back(i * 10);

for (std::list<int>::iterator i = mylist.begin(); i <= mylist.end(); ++i) {
    std::cout << *i << ", ";
}

std::cout << std::endl;

std::advance(it, 6);
std::cout << "The 6th element in mylist is: " << *it << std::endl;

// The vector that will contain mylist elements
std::vector<int> intAdeplacer;
intAdeplacer.insert(intAdeplacer.end(), mylist.begin(), it);

std::cout << std::endl;


std::cout << "Nombre d'éléments dans le vecteur : " << intAdeplacer.size() << std::endl;
std::cout << std::endl;

// see the content of the vector
std::cout << "Le vecteur de deplacement contient  : " << std::endl;

for (std::vector<int>::const_iterator i = intAdeplacer.begin();
        i <= intAdeplacer.end(); ++i) {
    std::cout << *i << ", ";
}

我得到了这个输出:

  

Le vecteur de deplacement contient:   0,10,20,30,40,1348985,

134985不被通缉..

// Insert in front of the list the values of the vector and keeping the same order of elements in the vector

for (std::vector<int>::const_iterator i = intAdeplacer.end();
        i >= intAdeplacer.begin(); --i) {
    mylist.push_front(*i);
}

std::cout << std::endl;
std::cout << std::endl;

std::cout << "nouvelle composition de mylist : " << std::endl;

for (std::list<int>::const_iterator j = mylist.begin(); j != mylist.end();
        ++j) {
    std::cout << *j << ", ";
}

std::cout << std::endl;
std::cout << std::endl;


// erasing the added elements from mylist

std::list<int>::iterator debut = mylist.begin();
std::list<int>::iterator fin = mylist.end();

std::advance(fin, 6);
mylist.erase(debut, fin);

for (std::list<int>::iterator j = mylist.begin(); j <= mylist.end(); ++j) {
    std::cout << *j << ", ";
}

return 0;

}

1 个答案:

答案 0 :(得分:0)

如果it是指向列表第6个元素的迭代器,则以下insert()将从begin()(包含)插入到it(已排除)到矢量:

intAdeplacer.insert(intAdeplacer.end(), mylist.begin(), it);

所以你只有5个元素,从0到40.不幸的是你的打印循环确实包含向量的end(),这超出了范围。这就是为什么你得到这个奇怪的尾随数字。

只需将您的循环更正为:

for (auto i = intAdeplacer.begin(); i != intAdeplacer.end(); ++i) {
    std::cout << *i << ", ";
}

或者考虑这种替代range-for语法:

for (auto &element: intAdeplacer) {
    std::cout << element << ", ";
}