Вектор Initializer_list - PullRequest
       2

Вектор Initializer_list

0 голосов
/ 04 января 2019

Я пытаюсь реализовать вектор, используя свой собственный класс, поэтому я не могу выполнить часть списка инициализатора

# include <iostream>
# include <exception>
# include<initializer_list>
template <class T>
 class vector {
  public:
  T* a;
T n;
int pos, c;
vector() { a = 0; n = 0; }
vector(T n) : n(n) { a = new T[n]; }
vector(std::initializer_list <vector> l) {
    a = new T[int(sizeof(l))];
        for (int f : l)
            *(a + f) = l.begin() + f;
     }
 void push_back(T k) {
    int i = k;
    *(a + n) = k;
}
 vector& operator= (vector&& th) {
     this->a = th.a;
    th.a = nullptr; return (*this);
}
vector& operator=(vector& k)
{
    this->a = k.a;
    return(*this);
}
int  size() { return n; }
void pop_back() { *(a + n) = nullptr;
n--;
}
void resize(int c) {  
    delete a;
    n = c;
 a = new T[c];
 }
 T operator[](int pos) {
    if (pos > sizeof(a))
        std::cout << "out of range";

    else return *(a + pos);
 }
 };
 int main() {
vector<int> a(10);
vector<char>b{ 'w','b','f','g' };
getchar();
return 0;

}

Я просто пытаюсь использовать нотацию смещения указателя для переноса элементов списка инициализатора в динамический массив, но получаю ошибки VS 17 IDE

Severity    Code    Description Project File    Line    Suppression   
Error   C2440   '=': cannot convert from 'const _Elem *' to 'T' 
Error   C2440   'initializing': cannot convert from 'const _Elem' to 'int'

1 Ответ

0 голосов
/ 05 января 2019

Привет, Нимрод!

#include <iostream>
#include <exception>
#include <initializer_list>
// normally people don't place a space between '#' and 'include'

template <class T>
class vector {
public:
    T* a;
    int n;
    // probably it is length the vector
    // change T to int
    int pos, c;
    vector() { 
        a = nullptr;
        // do not use '0' to instruct null pointer 
        n = 0; 
    }

    vector(int n): n(n) { a = new T[n]; }

    vector(std::initializer_list<T> l) {
        a = new T[l.size()];
        // redundant force cast from size_t to int

        for (int i = 0; i < l.size(); i++) {
            a[i] = l.begin()[i];
        }
        // for (int f : l) # it seems that you wrote JavaScript before?
        //     *(a + f) = l.begin() + f;
    }

    void push_back(T k) {
        // assigns "T k" to "int i"? it's confusing

        // int i = k;
        // *(a + n) = k;
    }

    // probably still many problems
    vector& operator=(vector&& th) {
        this->a = th.a;
        th.a = nullptr;
        return (*this);
    }

    vector& operator=(vector& k) {
        this->a = k.a;
        return(*this);
    }

    int size() { return n; }

    void pop_back() { *(a + n) = nullptr;
        n--;
    }

    void resize(int c) {  
        delete a;
        n = c;
        a = new T[c];
    }

    T operator[](int pos) {
        if (pos > sizeof(a))
            std::cout << "out of range";
        else return *(a + pos);
    }
 };

int main() {
    vector<int> a(10);
    vector<char>b{ 'w','b','f','g' };
    getchar();
    return 0;
}

Тебе все еще нужно больше тренироваться. XP

  1. В вашем контексте кода переменная шаблона для initializer_list должна быть T, а не int.
  2. Диапазон для цикла с initializer_list<T> будет получать значения в списке. Следовательно, оно должно принадлежать T.
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...