【问题标题】:Does it exist a c++ container with just the first and the last value?它是否存在一个只有第一个和最后一个值的 c++ 容器?
【发布时间】:2017-04-01 21:38:54
【问题描述】:

我需要一个容器,它只使用范围的第一个和最后一个值进行初始化。

我需要一个如下所示的容器:

range<int> myRange(first, last, bound);
int occur=myRange.count(r%5==0 && r%10!=0);

bound 将定义容器内迭代期间对象之间的距离。例如,如果first=0last=10bound=1 将在从firstlast 的每个整数上执行迭代。如果bound=2,将在 {0,2,4,6,8,10} 内执行迭代。但大小为 2; myRange[0]=firstmyRange[1]=last

简而言之,允许迭代不存在的对象的容器。迭代 first、first+bound、first+2*bound、first+n*bound,直到到达最后一个元素。我不想使用数组。

count() 方法将返回给定条件下return true 范围内的对象数。

N.B.我是初学者,所以如果有解决方案,请至少详细说明 :) 感谢您抽出宝贵时间;)

【问题讨论】:

标签: c++ algorithm performance stl containers


【解决方案1】:

参见以下实现:

猫范围.h

#ifndef _RANGE_H_
#define _RANGE_H_

#include <climits>
#include <cassert>
#define expr(var) (var%5 == 0 && var%10 != 0)

class Range {
    int first;
    int last;
    int bound;
    friend class RangeIterator;

    public: 
    Range(int f, int l, int b) : first(f), last(l), bound(b) {}
    ~Range() {}

    int count() const {
        int cnt = 0;
        for (int i = first; i <= last; i += bound) {
            if (expr(i))
                cnt++;
        }
        return cnt;
    }

    int getFirst() const { return first; }
    int getLast() const { return last; }
};

class RangeIterator {
    const Range* mRange;
    int mCurrVal;

    public: 
    RangeIterator(const Range* range) : mRange(range) 
    { 
        assert(range); 
        mCurrVal = mRange->first;
    }

    ~RangeIterator() {}

    int getNext() {
        int ret = INT_MIN;
        if (mCurrVal <= mRange->last) {
            ret = mCurrVal;
            mCurrVal += mRange->bound;
        }
        return ret;
    }
};

#endif

cat main.cxx

#include <iostream>
#include <climits>
#include "range.h"
using namespace std;

int main() {
    Range r(0, 50, 5);

    RangeIterator ri(&r);
    int curr = INT_MIN;
    while ((curr = ri.getNext()) != INT_MIN) {
        cout << curr << '\t';
    }
    cout << endl;

    cout << "count is : " << r.count() << endl;
    return 0;
}

我在 count 函数的实现中使用定义对条件进行了硬编码。如果您希望 count 函数足够通用以评估任何通用表达式,那么我想我需要在代码中使用正则表达式。 在我开始实施之前,我想确认这是否真的是您正在寻找的。​​p>

【讨论】:

  • 有什么理由可以无视 C++ 和 STL 关于 iteratoralgorithm 的约定?
  • C++ 约定是什么意思?我不知道现有的 STL 迭代器,所以我实现了它。
  • 基本上,类型要求,或概念。比如,自增操作符、解引用操作符、成员类型等。由原始 STL 发起,现在由国际标准指定,在 C++ 开发人员中广为人知,并被许多第三方库所遵循。
  • 哦,你的意思是迭代器在 STL 库中的实现方式。我同意由于 STL,样式很常见。但是,我认为这不是标准。我们在我工作的组织中使用不同的风格(正如我所提到的)。
  • 这不是“风格”。它是 C++ 国际标准中迭代器的定义。它是 ISO/IEC 14882:2014 第 24.2 节规定的形式要求。不要将其贬低为低于此值的东西。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-28
  • 1970-01-01
相关资源
最近更新 更多