这里我有简单的代码,它适用于 std::vector,但不适用于 std::list。
是不是因为列表中的元素没有对齐而出错?
编辑:
好的,将列表放入 func 的最佳方法是什么?将其转换为 vector ?
例如我在将数据放入 PolyPolyLine 时需要它
#include <iostream>
#include <vector>
#include <list>
using namespace std;
vector<int> func(int* buf)
{
vector<int> t;
t.push_back(buf[0]);
t.push_back(buf[1]);
return t;
}
int main() {
list<int> ls;
vector<int> v;
ls.push_back(2);
ls.push_back(111111);
v.push_back(12);
v.push_back(11);
vector<int> t1= func(&v[0]);
vector<int> t2= func(&ls.front());
cout<<t1[0]<<t1[1];
cout<<t2[0]<<t2[1];
return 0;
}
最佳答案
std::list<T>
是一个链表,所以它的内存是不连续的。您不能使用常规指针来进行指针运算 - 这是未定义的行为。
如果您将程序改为采用迭代器,并使用 std::next
要访问当前元素之外的元素,您的程序将产生您期望的行为。
template <typename T>
vector<int> func(T buf)
{
vector<int> t;
t.push_back(*next(buf, 0));
t.push_back(*next(buf, 1));
return t;
}
...
vector<int> t1= func(v.begin());
vector<int> t2= func(ls.begin());
关于c++ - 获取指向 std::list 的第一个元素的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27048063/