我有以下结构
enum quality { good = 0, bad, uncertain };
struct Value {
int time;
int value;
quality qual;
};
class MyClass {
public:
MyClass() {
InsertValues();
}
void InsertValues();
int GetLocationForTime(int time);
private:
vector<Value> valueContainer;
};
void MyClass::InsertValues() {
for(int num = 0; num < 5; num++) {
Value temp;
temp.time = num;
temp.value = num+1;
temp.qual = num % 2;
valueContainer.push_back(temp);
}
}
int MyClass::GetLocationForTime(int time)
{
// How to use lower bound here.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我遇到了很多编译错误.我想我在这里做错了我是STL编程的新手,请你纠正我的错误在哪里?这样做有好处吗?
谢谢!
Cas*_*Cow 12
谓词需要采用两个参数并返回bool.
由于您的函数是成员函数,因此它具有错误的签名.
此外,您可能需要使用您的仿函数将Value与int,Value to Value,int to Value和int to int进行比较.
struct CompareValueAndTime
{
bool operator()( const Value& v, int time ) const
{
return v.time < time;
}
bool operator()( const Value& v1, const Value& v2 ) const
{
return v1.time < v2.time;
}
bool operator()( int time1, int time2 ) const
{
return time1 < time2;
}
bool operator()( int time, const Value& v ) const
{
return time < v.time;
}
};
Run Code Online (Sandbox Code Playgroud)
这是相当麻烦的,所以让我们减少它:
struct CompareValueAndTime
{
int asTime( const Value& v ) const // or static
{
return v.time;
}
int asTime( int t ) const // or static
{
return t;
}
template< typename T1, typename T2 >
bool operator()( T1 const& t1, T2 const& t2 ) const
{
return asTime(t1) < asTime(t2);
}
};
Run Code Online (Sandbox Code Playgroud)
然后:
std::lower_bound(valueContainer.begin(), valueContainer.end(), time,
CompareValueAndTime() );
Run Code Online (Sandbox Code Playgroud)
还有一些其他错误,例如在类声明结束时没有分号,以及默认情况下类的成员是私有的,这使得整个类在这种情况下是私有的.你public:在构造函数之前错过了吗?
您的函数GetLocationForTime不返回值.您需要获取lower_bound的结果并从中减去begin().该函数也应该是const.
如果要在此处插入此调用的意图,则考虑在向量的中间插入是O(N)操作的事实,因此向量可能是错误的集合类型.
请注意,该lower_bound算法仅适用于预先排序的集合.如果您希望能够在不连续求助的情况下查找不同的成员,您将需要在这些字段上创建索引,可能使用boost的multi_index
| 归档时间: |
|
| 查看次数: |
12618 次 |
| 最近记录: |