簡體   English   中英

獲取指向std :: list的第一個元素的指針

[英]Get pointer to 1st element of std::list

這里有簡單的代碼,它適用於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;
}

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

演示

您不能將列表中某項的地址用作數組。 std :: list是具有動態分配的節點的雙向鏈表。 與向量不同,列表中的元素不是連續的。

保證連續內存分配的唯一容器是std::vector (和std::array )。 您沒有使用std::list這樣的保證,這就是為什么這種方法行不通的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM