码迷,mamicode.com
首页 > 编程语言 > 详细

新旧代码的兼容(c和c++)

时间:2018-07-21 14:44:39      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:array   一个   函数   ring   ctr   ace   ber   cto   numbers   

一、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类型最后一个字符后多一个 \0
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,但使用后重载函数类型错误,尚未解决

新旧代码的兼容(c和c++)

标签:array   一个   函数   ring   ctr   ace   ber   cto   numbers   

原文地址:https://www.cnblogs.com/dameidi/p/9346162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!