如何对const向量排序?
How can you sort a const vector?
如果我在类中定义了一个const向量,我该如何对它进行排序?
尝试排序const vector将给出错误,因为我正在更改const vector的内容。
你没有。如果你需要修改…那么它不应该是const
。这两个目标是相互直接冲突的。
不要问一个没有意义的问题的解决方案,告诉我们你真正想要完成的是什么。您是否试图从不希望调用者能够修改的方法返回向量?在这种情况下,创建一个getter方法并返回一个const vector&
#include <vector>
class Foo
{
public:
// clients can't change this vector directly
const std::vector<int>& get_vector() const { return _vec; }
// you can still create an interface that allows
// mutation of the vector in a safe way, or mutate
// the vector internally.
void push_back( int i ) { _vec.push_back( i ); }
private:
std::vector<int> _vec;
}
它是const向量吗?还是里面需要const的数据?
如果你有一个const向量,那么可能有一个不应该修改它的原因....
话虽如此。以下是关于如何搬起石头砸自己脚的伪代码:
const std::vector< Foo* > v; // hypothetical declaration
std::vector< Foo* >* vPtr = const_cast< std::vector< Foo* >* >(&v);
// GOOD LUCK
(*vPtr)[0] = new Foo();
是的,你可以在c++中对const vector进行排序。
设一个const向量为v
const vector<int> v={5,4,3,2,1};
如果你想用sort(v.begin(),v.end())
对这个向量排序,那么它将导致一些运行时错误,因为违反了const。
但这就是魔法-
vector<int>*temp=(vector<int>*)&v;
sort(temp->begin(),temp->end());
可以使用另一个vector指针对vector v进行排序,并将其引用到该指针。
在此之后,如果你输出向量v,那么你将得到这样的输出-
for(int a:v)
cout<<a<<" ";
cout<<endl;
输出:1 2 3 4 5
相关文章:
- 计算排序向量的向量中唯一值的计数
- 查找两个排序向量中共有的元素
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 如何从C++的对的排序向量中获取有关给定值的相应对
- 对象接收堆栈溢出异常 c++ 的排序向量
- "x"的所有元素都存在于"y"(排序向量)中吗?
- 指向指针排序向量的指针向量的 C++ 向量
- 未排序向量上的lower_bound/upper_bound
- 智能指针的排序向量:神秘崩溃
- 按类型排序向量并按类型或派生类型搜索
- 如何在不使用标准算法的情况下在排序向量中添加 c 元素?
- C++排序向量<double>与在<Object>双成员变量上键控的向量
- 字符串指针的排序向量
- 具有前导数字的字符串的排序向量
- 保证重新排序向量
- 结构解释的C 排序向量
- 更新排序向量的一个条目
- 通过在排序向量上使用二叉搜索来定位未排序向量中的元素
- 排序向量上 std::find_if 和 std::bind2nd 的替代品
- 使用QuickSort算法以降序排序向量