如何指向实际元素而不仅仅是数组地址

How to point to actual element not just the the array address?

本文关键字:不仅仅是 数组 组地址 元素 何指      更新时间:2023-10-16

我有一些这样的:

struct Node{
 int value;
 Node *left, Node *right;
 Node(): value(0), left(0), right(0){}
}
std::vector<Node> nodeList = getNodes();

我希望上面做一个循环缓冲区。所以

nodeList[i].left = &nodeList[i - 1]; 
nodeList[i].right= &nodeList[i + 1];

请注意,nodeList[0].left 指向 nodeList 的末尾,nodeList.back().right 指向 nodeList 的开头;

现在问题来了,nodeList[i].left 和 nodeList[i].right 只指向其前一个邻居的地址,但不一定指向实际的邻居对象。因此,如果我对节点列表进行排序,左右指针将不再指向原始节点。相反,他们将指向新的左邻居和右邻居。希望问题清楚了,我怎样才能让它例如nodeList[1].left指向nodeList[0],即使nodeList[0]被移动到另一个位置?

你可以做一个

std::vector<int> originalData = getOriginalData();

然后,要在保留对原始订单的访问的同时对其进行排序,只需对

std::vector<int const*> itemPointers;

您可以像这样初始化:

for( auto&& x : originalData )
{
    itemPointers.push_back( &x );
}

现在只需排序:

std::sort(
    itemPointers.begin(), itemPointers.end(),
    []( int const* p1, int const* p2 ) { return (*p1 < *p2); }
    );

完整的代码还显示了访问原始数据前置任务项的详细信息:

#include <algorithm>        // std::sort
#include <iostream>
#include <utility>          // std::begin, std:.end
#include <vector>           // std::vector
//using namespace std;

std::vector< int > getOriginalData()
{
    static int const data[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    return std::vector<int>( std::begin( data ), std::end( data ) );
}
int main()
{
    std::vector<int> const originalData = getOriginalData();
    std::vector<int const*> itemPointers;
    for( auto const& x : originalData )
    {
        itemPointers.push_back( &x );
    }
    std::sort(
        itemPointers.begin(), itemPointers.end(),
        []( int const* p1, int const* p2 ) { return (*p1 < *p2); }
        );
    std::wcout << "Sorted: ";
    for( auto const p : itemPointers )
    {
        std::wcout << *p << " ";
    }
    std::wcout << std::endl;
    std::wcout << "Predecessors in original data: ";
    for( auto const p : itemPointers )
    {
        int const* const pPred = (p == &originalData[0]? nullptr : p - 1);
        if( pPred == nullptr )
        { std::wcout << "! "; }
        else
        { std::wcout << *pPred << " "; }
    }
    std::wcout << std::endl;
}