【发布时间】:2016-02-17 21:17:27
【问题描述】:
在我的 C++ 脚本中,我想将列表的一些元素插入到向量中(从列表的开头到特定位置“it”),然后尝试将向量添加到列表的顶部并保持向量的顺序相同,但我在向量中得到了不需要的附加元素。
这是我的代码:
#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, 134985,
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;
}
【问题讨论】:
-
这个
i <= intAdeplacer.end()应该是i < intAdeplacer.end()。查找遍历向量的任何示例。 -
但我需要查看向量的所有内容以确保将添加到列表中的元素。
-
通常人们将
script文件称为python、shell、basic等解释语言。C++生成可执行文件,而不是脚本。 -
正如我所说,查找任何迭代向量的示例。
-
在第一次迭代期间,迭代器不会引用任何内容,因为 end() 刚刚超过向量的末尾。尝试使用 reverse_iterator 并在 for 循环中测试 != intAdeplacer.end()。