【问题标题】:Casting vector<int> to const vector<const int>将 vector<int> 转换为 const vector<const int>
【发布时间】:2016-11-11 13:57:20
【问题描述】:

如何将 vector&lt;int&gt; 转换为 const vector&lt;const int&gt;

我试过static_cast&lt;const vector&lt;const int&gt;&gt;(array) 并使用没有强制转换的值。都没有编译。

【问题讨论】:

  • 你不能。 vector&lt;int&gt;vector&lt;const int&gt; 是完全不同的类型。改为传递spanarray_view
  • 要为const 提供对std::vector&lt;int&gt; 的访问权限,请使用std::vector&lt;int&gt;::const_iterator
  • 查看这篇文章:stackoverflow.com/questions/2868485/… --
  • std::vector&lt;const int&gt; 无论如何都无效,因为元素必须是可分配的。
  • @chema989 实际上,这看起来像是对您链接到的问题的欺骗。

标签: c++ casting constants


【解决方案1】:

您不能将 std::vector&lt;int&gt; 转换为 const std::vector&lt;const int&gt;

此外,使用std::vector&lt;const int&gt; 根本没有意义。它不会比const std::vector&lt;int&gt; 更安全。

不仅如此,C++ 不允许构造std::vector&lt;const T&gt;。请参阅Does C++11 allow vector<const T>? 了解更多信息。

【讨论】:

  • ...vector 甚至可以 拥有 const-qualified 元素类型吗?当我在昏暗而遥远的过去尝试时,它对我从来没有用过,现在int const 对我也不起作用。
  • @underscore_d,g++ 不允许使用std::vector&lt;const int&gt; 创建变量。不知道标准中有没有禁止这样的变量。
  • 我认为这可能与我之前尝试过的元素类型中的复制/移动 ctor 不可用有关,这意味着重新分配和排序等需要使用 operator=,这显然不是const... 但int 有这些,这破坏了我的理论。叹了口气 - 我去的标准。
  • @underscore_d const int 没有可用的operator=
  • 为了澄清,我指的是它有演员,而不是分配。
【解决方案2】:

您不能更改向量元素的类型,但可以将向量的类型更改为const std::vector&lt;int&gt;,这将阻止对向量进行更改。

#include <vector>

int main()
{
    std::vector<int> v1;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);

    const std::vector<int>& v2 = v1;
    v2.push_back(4); // Causes an error
    v2[0] = 4; // Causes an error
    return 0;
}

【讨论】:

  • 虽然它不能解决我的缓存问题,但我将它留在这里,因为它可能对其他人有帮助
  • 这使得 container 为 const,但我猜想通过尝试使用不允许的概念 'a container with const elements ',OP 希望能够添加/重新分配容器(非const),而不能在构造后更改元素(const)。有人可能会认为这在 C++11 之后是可能的,因为编译器可以对元素使用复制和移动构造函数而不是赋值 - 但实际上,容器从未打算包含 const 元素 - 目前,不兼容的默认分配器阻止无论如何:stackoverflow.com/questions/6954906
猜你喜欢
  • 2020-12-14
  • 2012-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
相关资源
最近更新 更多