如何使用sort对类中的向量进行排序
我想知道如何使用排序函数对类中私有的向量进行排序:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class A{
private:
const vector<int> myvec;
A(vector<int>& vec) : myvec(vec) { }
public:
const vector<int>& getvec() { return myvec; }
int get_sec_element(){
int sec_ele = 0;
sort(myvec.begin(), myvec.end());
sec_ele = myvec[2];
return sec_ele;
}
};
因此,如果我创建 A myvec_object
并用其中已有值的向量填充它,则调用 myvec_object。 get_sec_ele() 将返回向量中的第二个元素。然而,编译器给出了一条巨大的错误消息:“从这里实例化”。可能是什么问题?
I was wondering how I can use the sort function to sort a vector which is private in a class:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
class A{
private:
const vector<int> myvec;
A(vector<int>& vec) : myvec(vec) { }
public:
const vector<int>& getvec() { return myvec; }
int get_sec_element(){
int sec_ele = 0;
sort(myvec.begin(), myvec.end());
sec_ele = myvec[2];
return sec_ele;
}
};
So if I created A myvec_object
and filled it with a vector which had values already inside it, caliing myvec_object.get_sec_ele() would return the 2nd element in the vector. However, the compiler is giving a huge error message with: "instantiated from here". What could be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您将
myvec
声明为const
——您希望如何修改它?将
myvec
声明为:You declared
myvec
asconst
-- how would you expect to modify it?Declare
myvec
as:您已将向量定义为 const;这使得它在初始化后不可变。如果您打算对向量进行排序,则需要取消它,或者制作一个副本来排序(当然,如果您打算多次执行此操作,这会很慢)。
You have defined your vector as
const
; this makes it immutable after initialization. If you intend to sort the vector, you'll need to un-const it, or make a copy to sort (which would be slow, of course, if you intend to do this more than once).您已将成员变量
myvec
声明为const
,但std::sort
必须修改向量才能对其进行排序。您可以:const
关键字来使向量成为非 conststd::vector
替换为std::multiset
,它将保持项目按开始的排序顺序。You've declared the member variable
myvec
asconst
, butstd::sort
has to modify the vector to sort it. You could:const
keyword from its declarationstd::vector
withstd::multiset
, which will keep the items in sorted order to begin with.