zoukankan      html  css  js  c++  java
  • 新旧代码的兼容(c和c++)

    一、vector转换为动态数组

     1 #include<iostream>
     2 #include<vector>
     3 
     4 using namespace std;
     5 
     6 int main()
     7 {
     8     vector<int> ivec;
     9     int ival;
    10     cout << "Enter numbers:(ctrl+z to end)" << endl;
    11     while (cin >> ival)
    12     {
    13         ivec.push_back(ival);
    14     }
    15 
    16     int *parr = new int[ivec.size()];
    17     size_t ix = 0;
    18     for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter,++ix)
    19     {
    20         parr[ix] = *iter;
    21     }
    22     for (int *q = parr; q != parr + ivec.size(); ++q)
    23     {
    24         cout << *q << endl;
    25     }
    26     delete[] parr;
    27     system("pause");
    28 }

    二、将string类型字符串放入vector中,从vector中转换到c风格字符串动态数组中

     1 #include<iostream>
     2 #include<vector>
     3 #include<string>
     4 
     5 using namespace std;
     6 
     7 int main()
     8 {
     9     vector<string> svec;
    10     string str;
    11     cout << "Enter strings:(ctrl+z to end)" << endl;
    12     while (cin >> str)
    13     {
    14         svec.push_back(str);
    15     }
    16 
    17     char **parr = new char*[svec.size()];
    18 
    19     size_t ix=0;
    20     for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); ++iter,++ix)
    21     {
    22         char *p = new char[(*iter).size()+1];//注意 char类型最后一个字符后多一个 
    23         strcpy(p,(*iter).c_str());
    24         parr[ix] = p;
    25     }
    26     cout << "Content of vector:" << endl;
    27     for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); ++iter)
    28     {
    29         cout << *iter << endl;
    30     }
    31 
    32     cout << "Content of character arrays:" << endl;
    33     for (ix = 0; ix != svec.size(); ++ix)
    34     {
    35         cout << parr[ix] << endl;
    36     }
    37 
    38     for (ix = 0; ix != svec.size(); ++ix)
    39         delete[] parr[ix];
    40     delete[] parr;
    41 
    42     
    43     system("pause");
    44     return 0;
    45 }
    46  

    注释:strcpy(p,(*iter).c_str());  这句话在VS2015运行错误 需使用strcpy_s,但使用后重载函数类型错误,尚未解决

    坚持比努力更重要
  • 相关阅读:
    select * from a,b探讨
    使用python脚本从数据库导出数据到excel
    git入门
    登录远程服务器脚本
    Ubuntu下python开发环境搭建
    asyncio并发编程
    深入理解python协程
    单例模式的几种实现方式
    MySQL统计百分比结果
    Java查询MySQL数据库指定数据库中所有表名、字段名、字段类型、字段长度、字段描述
  • 原文地址:https://www.cnblogs.com/dameidi/p/9346162.html
Copyright © 2011-2022 走看看