如何对 const 向量进行排序?
如果我在类中定义了一个 const 向量,我该如何对其进行排序?
尝试对 const 向量进行排序会出错,因为我正在更改 const 向量的内容。
If I have a const vector defined in my class, how can I go about sorting it?
Attempting to sort a const vector will give errors since I'm changing the contents of a const vector.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你不知道。如果您需要修改它......那么它不应该是 const。这两个目标是直接冲突的。
不要寻求一个没有意义的问题的解决方案,而是告诉我们您实际上想在这里完成什么。您是否试图从您不希望调用者能够修改的方法返回一个向量?在这种情况下,创建一个 getter 方法并返回一个
const vector&
You don't. If you need to modify it... well then it shouldn't be
const
. The two goals are in direct conflict with one another.Instead of asking for a solution to a problem that doesn't make sense, tell us what you are actually trying to accomplish here. Are you trying to return a vector from a method that you don't want the caller to be able to modify? In that case, create a getter method and return a
const vector&
它是 const 向量吗?或者里面的数据需要是const的?
如果你有一个 const 向量,那么可能有一个不应该修改它的原因......
话虽这么说。下面的伪代码告诉你如何搬起石头砸自己的脚:
Is it the vector that's const? Or the data inside it that needs to be const?
If you have a const vector, then there's probably a reason why it shouldn't be modified....
That being said. Here's pseudocode on how you can shoot yourself in the foot:
是的,您可以在 C++ 中对 const 向量进行排序。
设一个const向量为v。
如果你想使用
sort(v.begin(),v.end())
对该向量进行排序,那么由于违反const,它将导致一些运行时错误。但这就是神奇的——
你可以使用另一个向量指针对向量 v 进行排序,并引用它。
之后,如果您打印向量 v,那么您将得到如下输出 -
输出:
1 2 3 4 5
Yes, you can sort a const vector in C++.
Let a const vector is v.
If you want to sort this vector using
sort(v.begin(),v.end())
then it will result some runtime error due to violation of const.But Here is the magic-
You can sort the vector v using another vector pointer and referencing it to that.
After this, if you print the vector v then you will get output like this -
Output:
1 2 3 4 5