如何指向实际元素而不仅仅是数组地址
How to point to actual element not just the the array address?
我有一些这样的:
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;
}
相关文章:
- 如何计算数组中元素的位数?(不是数组的长度),并计算其数字的总和
- 如何使用C++初始化向量;脚本化值不是数组、指针或矢量错误
- Sizeof返回的是指针大小,而不是数组大小.有其他方法可以找到尺寸吗
- " ans += (a[i] - ans * r > 0); "是什么意思,其中 ans,r 是整数,a[i] 是数组元素?
- 为什么会出现一些垃圾而不是数组值?
- 我想返回数组索引,而不是数组值
- 将字符串转换为整数。为什么会出现此错误?我想将 ID(字符串)更改为 IC(整数)。两者都是数组。顺便说一句,我仍然是初学者
- 如何为包装容器的模板类编写构造函数,其中容器可以是数组或向量
- 我试图释放数据的某些部分,并用特定的整数值标记其休息,以表明它不是有效的指针.(不是数组)
- Subscripted Value不是数组
- 为什么 clang 将字符串文字作为指针而不是数组
- 如何指向实际元素而不仅仅是数组地址
- 有条件地确定字符串是否是数组的一部分
- 使用向量而不是数组从最小到最大对数字进行排序C++
- 使用矢量而不是数组
- 将函数更改为使用向量而不是数组
- 为什么我的函数打印地址而不是数组的内容
- 动态数组C++,新 Obj[size] 只创建 1 个对象指针而不是数组时出现问题
- For 或 While 循环具有 2 个最大变量,其中一个是数组(编程 I)
- 有些人怀疑指针是数组