C++开篇(一):数组对象打印



1、使用模板方法进行打印:
【代码】:
template<typename T>
void PrintArray(const T input_array[], const unsigned int array_size)
{
    for (int i = 0; i < array_size; ++i)
    {
        cout << "input_array[" << i << "] : " << input_array[i] << endl;
    }
}
【支持】:
float float_array[5] = { 1,2,3,4,5 };
PrintArray(float_array, 5);

int int_array[4] = { 1,2,3,4 };
PrintArray(int_array, 4);

double double_array[6] = { 1.0,1.1,1.2,1.3,1.4,1.5 };
PrintArray(double_array, 6);

char* str_array[3] = {"aaa","bbb","ccc"};
PrintArray(str_array, 3);
【不支持】:
string string_array[3] = {"aaa","bbb","ccc"};
PrintArray(string_array, 3);
对于string的cout方法,需要使用以下形式:
string string_array[3] = { "aaa","bbb","ccc" };
for (int i = 0; i < 3; ++i)
{
 cout << "element [" << i << "] is : " << string_input_array[i].c_str() << endl;
}
【说明】:string对象的cout时候,需要加上c_str()。
【限制】:
传入的参数明确要有数组的大小n,要求数组大小是已知的。

2、将数组改成vector
【代码】:
template<typename T>
void PrintVector(const vector<T>& input_vector)
{
    for (auto c : input_vector)
    {
  // << 运算符不是每个对象都支持,这就限制了模板的使用范围
        cout << c << endl;
    }
}
【支持】:
vector<int> int_vector;
int_vector.push_back(1);
int_vector.push_back(2);
PrintVector(int_vector);

vector<double> double_vector;
double_vector.push_back(1.1);
double_vector.push_back(1.5);
PrintVector(double_vector);

vector<char*> str_vector;
str_vector.push_back("CCC");
str_vector.push_back("DDD");
PrintVector(str_vector);
【不支持】:
vector<string> string_vector;
string_vector.push_back("AAA");
string_vector.push_back("BBB");
PrintVector(string_vector);
【说明】:
对于基础类型(不包括string)的数据,模板定义的方法支持。非基础类型数据,要求对象重载"<<"。
【其他】:
1)即使在PrintVector通过if(typeid(T) == typeid(string))进行判断,但是在编译的时候,编译器没法确认到底走哪一个分支。
2)调用PrintVector(string_vector);代码编辑时不会报错,但是编译时,会报错,所以对于模板的使用要慎重。
3)即使模板能够增加代码的通用性,但是想要“All In”,任然只是不成熟程序员的一厢情愿,任何方法都有适用范围,即使使用了模板。

3、指针删除
template<typename T>
void DeletePoint(T* input_point)
{
 if (nullptr != input_point)
 {
  delete input_point;
  input_point = nullptr;
 }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值