获取指向std :: list的第一个元素的指针

mrg*_*oom 1 c++ list vector std

这里我有简单的代码,它适用于std :: vector,但不适用于std :: list.

是不是因为列表中的元素没有合拢?

编辑:

好的,将列表放入func的最佳方法是什么?将它转换为矢量?

例如,我将数据放入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;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 7

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());
Run Code Online (Sandbox Code Playgroud)

演示.