mrgloom
mrgloom

Reputation: 21622

Get pointer to 1st element of std::list

Here I have simple code, it works for std::vector, but don't work for std::list.

Is it wrong because elements in list doesn't alighned?

Edit:

Ok, what is the best way to put list in func? Convert it to vector?

for example I need it when put data in 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;
}

Upvotes: 1

Views: 1838

Answers (3)

Jakub Arnold
Jakub Arnold

Reputation: 87210

The only container that guarantees continuous memory allocation is std::vector (and std::array). You don't have any sort of guarantee like that with a std::list, which is why this approach can't possibly work.

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726569

The std::list<T> is a linked list, so its memory is not contiguous. You cannot use regular pointers with it to do pointer arithmetic - it's undefined behavior.

If you change your program to take iterators instead, and use std::next to access elements beyond the current one, your program would produce the behavior that you expect.

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());

Demo.

Upvotes: 7

Jay Miller
Jay Miller

Reputation: 2234

You can't take the address of an item in a list and use it as an array. std::list is a doubly linked list with dynamically allocated nodes. Unlike a vector, the elements in the list are not contiguous.

Upvotes: 3

Related Questions