首页 > 解决方案 > 删除向量的元素并在c ++中保留空白空间

问题描述

我有一个向量:

x = 1 2 3 4 5 6 7;

我想删除该向量的一个元素并将空位置保持原样:

新向量

如何在 C++ 中做到这一点?我对我应该用来为这个问题找到正确问题的关键字感到很困惑。

标签: c++

解决方案


没有“空”之类的东西int,因此连续的ints 序列,例如 astd::vector<int>不能有“空”元素。

您可以使用std::optional<int>which 确实具有“没有价值”的概念

#include <iostream>
#include <vector>
#include <optional>
#include <algorithm>

template<typename T>
std::ostream& operator<<(std::ostream & os, const std::vector<std::optional<T>> & vec)
{
    for (auto & el : vec)
    {
        if (el)
            os << *el << ' ';
        else
            os << "  ";
    }
    return os << '\n';
}

int main()
{
    std::vector<std::optional<int>> vals = { 1, 2, 3, 4, 5, 6, 7 };

    std::cout << vals;

    *std::find(vals.begin(), vals.end(), 5) = std::nullopt;
    *std::find(vals.begin(), vals.end(), 6) = std::nullopt;

    std::cout << vals;

    return 0;
}

推荐阅读