如何在c++中实现模板类?

问题描述 投票:0回答:1

我在大学学习 C++ 几个月了,所以我是一个初学者,在考试中我遇到了模板类的问题。任务是在头文件中实现一个模板类,就像在 main 方法中给出的那样。

#include <iostream>
#include "shifter.h"
#include <string>
#include <deque>
#include <vector>

struct string_size_less
{

  bool operator()( const std::string& lhs,
                   const std::string& rhs ) const
  {
    return lhs.size() < rhs.size();
  }

};

const int max = 1024;

int main()
{
  std::vector<int> vm;
  for( int i = 0; i < max; ++i )
  {
    vm.push_back( i );
  }
  std::string s = "Hello World!";
  std::deque<double> d;
  d.push_back( 3.45 );
  d.push_back( 7.89 );
  d.push_back( 2.12 );
  shifter<std::string, char> ssh( s );
  shifter<std::deque<double>, double> dsh( d );
  shifter<std::vector<int>, int> vsh( vm );

  vsh.shift( -3 );
  vsh.shift( 1 );
  ssh.shift( 27 );
  ssh.shift( 3 );
  dsh.shift( -10 );
}

任务是在shifter.h文件中实现shifter模板类。问题是它可以接受所有类型的数组,如字符串、向量、双端队列等。然后 shift 方法将列表中的项目移动给定的数字,如果是正数,则向右移动 3 例如,如果其负向移动以同样的方式离开。 我不知道如何编写我的移位器类来像这样工作。关于如何开始的任何建议,头文件应该是什么样子?

我尝试编写课程,就像我们以前在课堂上那样。

template<class T, class U>

class shifter {
T cont;
U type
public
shifter(T arr) {}

但老实说,我完全不知道如何做到这一点。

c++ class templates shift
1个回答
0
投票

关于如何开始有什么建议吗?头文件应该是什么样子?

首先使其能够存储对其应操作的容器的引用或指针。在您的情况下,您可能只需要one模板参数。这是一个存储指向容器的指针的示例。

template <class C>
class shifter {
public:
    shifter(C& c) : m_container(&c) {}

private:
    C* m_container;
};

然后需要实现

void shift(...)
成员函数。对于左移或右移,您可以使用标准算法
std::rotate
,您可以向该算法提供三个迭代器:范围的开头、新的第一个元素和“最后一个通过的”迭代器。

shift
成员函数的一种可能实现:

#include <algorithm> // std::rotate
#include <iterator>  // std::next / std::prev

// ...

void shift(typename C::difference_type x) {              
    if(x < 0) {
        x = -x;
        x %= std::size(*m_container);
        // call std::rotate here with the proper iterators:
        // std::begin(*m_container)
        // std::next(std::begin(*m_container), x)  // the new first element
        // std::end(*m_container)

    } else if(x > 0){
        x %= std::size(*m_container);
        // call std::rotate here with the proper iterators:
        // std::begin(*m_container),
        // std::prev(std::end(*m_container), x)    // the new first element
        // std::end(*m_container));
    }
}

然而,它不适用于标准库中的所有容器,但它适用于大多数有意义的地方。

© www.soinside.com 2019 - 2024. All rights reserved.