打印实施在推回后立即失败(矢量)

Print Implementation fails right after pushback (vector)

我是 C++ 和向量的新手,因此,我遇到了一些麻烦,因为这个函数在返回后无法打印所需的值。我收到了我认为是垃圾值的东西。可能是因为我正在使用 unsigned char 而不是整数类型吗?我不知道。我需要让它为我即将到期的学校作业工作,我真的坚持这一点。这里有人能解决这个问题吗?谢谢!

期望的输出:

********** TestSubscript1 **********
Construct from unsigned char array:
2  4  6  6  8  10  6  12  234  14  16  6  6  (size=13, capacity=16)

我的输出:

********** TestSubscript1 **********
Construct from unsigned char array:

  ê     (size=13 capacity=16)

头文件(我的实现):

template <typename T>
vec 
{

private:
T* v;
int count;
int capacity;
public:

vector(){
    capacity=0;
    v = nullptr;
    count = 0;
}
void push_back(const T& t)
{
    if(count+1>capacity)
{
    capacity = std::max(2*capacity, 1);

    T* newData = new T[capacity];
    for(int i=0; i <count; i++)
    {
        newData[i] = v[i];
    }
    delete[] v;
    v = newData;
}
v[count++] = t;
}
T& operator[](size_t num) const
{   
    return v[num];
}

template <typename T1>

friend void Print(const vector<T1>& s);

};
template <typename T1>
void Print(const vector<T1>& s)
{
    for(int i = 0; i < s.count; i++) 
    {
    std::cout<<s.v[i]<<" ";
    }
    std::cout<< "(size=" << s.count << " " << "capacity=" << s.capacity << 
 ")";
    std::cout<<std::endl; 
    }

主文件(保持不变):

#include <iostream>
#include <cstdlib>              // atoi
#include "cs150_vect.h"

void TestSubscript1(void)
{
std::cout << "\n********** TestSubscript1 **********\n";
unsigned char ia[] = { 2, 4, 6, 6, 8, 10,
                       6, 12, 234, 14, 16, 6, 6
                     };
int size = sizeof(ia) / sizeof(*ia);
std::cout << "Construct from unsigned char array:\n";
cs150::vector<unsigned char> temp_vec;
for(int i=0; i<size; ++i)
    temp_vec.push_back(ia[i]);

const cs150::vector<unsigned char> a(temp_vec);
Print(a);
}

是的,因为您正在处理字符数据。 operator<<charunsigned char 的重载,它们将这些值打印为字符而不是数字。由于您想要数字,只需从 unsigned char.

切换到 int
int ia[] = { 2, 4, 6, 6, 8, 10,
                       6, 12, 234, 14, 16, 6, 6
                     };
int size = sizeof(ia) / sizeof(*ia);
std::cout << "Construct from int array:\n";
cs150::vector<int> temp_vec;

如果您已正确完成模板,则无需进行其他更改。

如果您真的想坚持使用字符数据,那么一种方法是为 unsigned char 编写 Print 函数的特例,以便将字符打印为数字。

template <>
inline void Print(const vector<unsigned char>& s)
{
    for(int i = 0; i < s.count; i++) 
    {
        std::cout<<(unsigned)s.v[i]<<" "; // print chars as numbers
    }
    std::cout<< "(size=" << s.count << " " << "capacity=" << s.capacity << ")";
    std::cout<<std::endl; 
}

此专业化是对通用版本的补充。它说当 Tunsigned char 时使用这个版本而不是通用版本。

不完全确定是否需要将此版本声明为好友。毫无疑问,您会发现的。