C++ Stl 矢量插入空 (NULL) 节点
C++ Stl Vector insert empty(NULL) node
由于我的算法,我必须在向量中插入一些空(NULL(节点,我的意思是一些间隙。我该如何执行此操作?
我试过像
array.push_back(NULL);
但它添加了值为 0 的节点。
编辑:
我从整数数组(如 int a[10000](中获取值,并将它们插入向量sirali_dizi并在向量中留出一些间隙。所以我想留下一些空白,但每一轮我也想对我的数组进行排序。所以我不能使用 -1 或 0 等。
那是因为NULL
#define
d为0。
如果向量是指针的集合,则NULL
(0( 始终是非法指针值,可以安全地进行检查,而不必担心误报。
如果你的数组是允许 0 的整数,那么你将不得不使用其他一些哨兵值来区分。 NULL
旨在与指针一起使用。
使用NULL
来检测空节点不是强制性的。
如果您不使用值"0"或使用其他值(例如 -1、INF
等(来记录空节点,则可以使用 NULL
。
你还没有说太多关于你的算法。我想增强可选可能会有所帮助。
http://www.boost.org/doc/libs/1_48_0/libs/optional/doc/html/index.html
还有一个额外的状态。您可以修改排序算法以检查(值(是否存在。
如果您有 NULL 值,则需要一个可以封装此信息的类型。
在这里,注释可以是无效的,也可以是有效的(带有值(。
class Node
{
bool valid;
int value;
public:
Node(int v): valid(true), value(v) {}
Node(): valid(false) {}
bool isValid() const {return valid;}
Node& operator=(int newValue)
{
valid = true;
value = newValue;
return *this;
}
void makeInvalid()
{
valid = false;
}
bool operator<(Node const& rhs) const
{
// If both are invalid then neither is less.
// If one is invalid the invalid one is less
// Otherwise use the value to sort by
if (!valid && !rhs.value) { return false;}
if ( valid && !rhs.valid) { return false;}
if (!valid && rhs.valid) { return true;}
return value < rhs.valid;
}
friend std::ostream& operator<<(std::ostream& stream, Node const& value)
{
if (value.isValid())
{ stream << value.value;
}
else
{ stream << "-- NULL --";
}
return stream;
}
};
然后你可以使用它:
#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
int main()
{
std::vector<Node> data;
data.push_back(1);
data.push_back(2);
data.push_back(Node()); // Invalid or NULL value.
std::sort(data.begin(), data.end());
std::copy(data.begin(), data.end(),
std::ostream_iterator<Node>(std::cout, " ")
);
}
然后运行你会得到:
> g++ sort.cpp
> ./a.out
-- NULL -- 1 2
你可以制作一个指向 int 而不是 int 的指针向量:
vector<int*> vInt;
vInt.push_back(NULL);
然后以这种方式访问值:
vector<int*>::iterator iIter;
for(iIter = vInt.begin(); iIter != vInt.end(); iIter++){
if(*iIter != NULL){
// Notice the double asterisk: it's a pointer (the iterator) to another pointer (the value)
cout << **iIter << endl;
}
}
相关文章:
- 反向给定链表中的K节点
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Boost Graph Library,修复节点大小
- C++A*算法并不总是在路径中具有目标节点
- 如何找到2个单链表的公共节点
- 如果我std::dynamic_pointer_cast并且底层dynamic_cast的结果为null,那么返回的sh
- 如何在 c++ 中'NULL'字符串
- 计算每个节点的树高,帮助我解释这个代码解决方案
- c++使用foreach使数组为null
- 当使用通配符和null指针调用函数时,对输出的说明
- 为什么我的删除节点函数实际上没有删除节点?
- 我们可以删除链表中静态内存中的节点吗
- 如何在pugixml中获取节点的内部XML
- 当字段可以为null时,如何使用C++接口在Avro中写入数据
- 具有 4 个指针的节点的递归插入函数返回 null
- 根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?
- 声明新节点但不等于 NULL
- 添加到链表的节点在函数后恢复为 NULL
- 数据在null节点中的链表
- C++ Stl 矢量插入空 (NULL) 节点