Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何将'std::lower_-bound'与此定制容器一起使用?_C++_Algorithm_Oop_Search_Iterator - Fatal编程技术网

C++ 如何将'std::lower_-bound'与此定制容器一起使用?

C++ 如何将'std::lower_-bound'与此定制容器一起使用?,c++,algorithm,oop,search,iterator,C++,Algorithm,Oop,Search,Iterator,我想要一个std::vector对象的包装器。下面是一些在包装器下实现的基本方法 您必须为您的包装器创建并实现迭代器,以满足这个概念。关于如何做到这一点的详细信息可以在本主题的答案中找到。然后提供包装器的方法,这些方法首先返回过去的迭代器,然后返回过去的迭代器,通常它们称为begin和end,它们最好是begin和end,但您可以以任何方式调用它们 迭代器可以实现为std::pair,它在数据中的位置加上对数据本身的引用,并通过适当的运算符++实现 作为优化的选择,您可能希望使迭代器满足概念,而

我想要一个std::vector对象的包装器。下面是一些在包装器下实现的基本方法


您必须为您的包装器创建并实现迭代器,以满足这个概念。关于如何做到这一点的详细信息可以在本主题的答案中找到。然后提供包装器的方法,这些方法首先返回过去的迭代器,然后返回过去的迭代器,通常它们称为begin和end,它们最好是begin和end,但您可以以任何方式调用它们

迭代器可以实现为std::pair,它在数据中的位置加上对数据本身的引用,并通过适当的运算符++实现


作为优化的选择,您可能希望使迭代器满足概念,而std::lower_bound或std::upper_bound可能更有效,这当然取决于您如何实现随机访问。

这个包装器到底想实现什么?我有一个函数,旨在处理std::vector和std::vector。包装器的目标是允许对该函数进行模板化,并使用STL函数lower_bound、upper_bound和方法erase、insert以及运算符[],而无需处理数据结构的潜在复杂性。这听起来像是一个非常糟糕的主意吗@RichardHodges@Slava它们是在排序数组中执行二进制搜索的STL算法。函数将ForwardIt作为输入,并将其输出ForwardIt。为什么你认为我误解了它们的工作原理?我的目标是运行std::lower_boundw.begin,w.end,object;,其中w是包装器。这有意义吗?我收回,我误读了你现有的上界用法,不用担心。你和理查德都很难回答我的问题,我怀疑这是我的错。这个问题现在清楚界定了吗?
template<class T>
class Wrapper
{
private:
    std::vector<std::vector<T>>& data;
    int totalSize;
    std::vector<int> indicesMap;

public:
    Wrapper(std::vector<std::vector<T>>& input):data(input)
    {
        totalSize = 0;
        for (int i = 0 ; i < data.size() ; i++)
        {
            totalSize += data[i].size();
            indicesMap.push_back(totalSize);
        }
    }

    T operator[](int index)
    {
        int whichVector = std::upper_bound(
            indicesMap.begin(),
            indicesMap.end(),
            index
        ) - indicesMap.begin();

        int i = whichVector == 0 ? index : index - indicesMap[whichVector-1];

        return data[whichVector][i];
    }

    int size()
    {
        return totalSize;
    }
};
int main()
{
    std::vector<std::vector<int>> x;
    std::vector<int> x1 = {1,2,3};
    std::vector<int> x2 = {10,20,30};
    std::vector<int> x3 = {100,200,300};
    x.push_back(x1);
    x.push_back(x2);
    x.push_back(x3);

    Wrapper<int> w(x);
    std::cout << w[4] << "\n"; // prints 20 as expected

    return 0;
}
std::lower_bound(w.begin(), w.end(), object);