C++ Stl 矢量插入空 (NULL) 节点

C++ Stl Vector insert empty(NULL) node

本文关键字:NULL 节点 插入 Stl C++      更新时间:2023-10-16

由于我的算法,我必须在向量中插入一些空(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;
    }
}