C/C++基础学习代码(1)

程序1.

/*
*编写程序由从标准输入的设备读入的元素数据建立一个int型vector对象,
*然后动态创建一个与该vector对象大小一致的数组,
*把vector对象的所有元素复制给新数组。
*/
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> iVec;
    cout << "请输入整数:" << endl;
    int temp;
    //赋值给iVec
    while(cin >> temp)
    {
        iVec.push_back(temp);
    }

    const static int arrLength = iVec.size();
    cout << arrLength << endl;
    int* pArray = new int[arrLength];
    //保存pArray,使用pTemp赋值
    int* pTemp = pArray;
    //打印iVec,并给创建的数组赋值
    for(vector<int>::iterator iter = iVec.begin(); iter != iVec.end(); ++iter, ++pTemp){
        cout << *iter << " ";
        *pTemp = *iter;
    }
    cout << endl;
    //打印数组
    for(int i =0 ; i < arrLength; ++i){
        cout << pArray[i] << " ";
    }
    //处理内存
    delete [] pArray;
    pArray = NULL;

    return 0;
}
/****输出****
请输入整数:
5
123 324 342 654 543 
123 324 342 654 543 
************/

程序2.

/*
 *编写程序连接两个C风格字符串字面值,把结果存储在一个C风格字符串中。
 *然后再编写程序连接两个string类型字符串,这两个string类型的字符串
 *与前面的C风格字符串字面值具有相同的内容。
 */

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

int main()
{
    const char *str1 = "who and who ";
    const char *str2 = "will get together !";
    char *str3;
    string str5, str6, str7;

    str3 = new char[strlen(str1) +strlen(str2) +1];
    strcpy(str3,str1);
    strcat(str3,str2);
    for(int i = 0; i != strlen(str3); ++i)
        cout << *(str3 + i);
    cout << endl;

    str5 = "who and who ";
    str6 =  "will get together !";
    str7 = str5 + str6;
    cout << str7;

    delete [] str3;
    str3 = NULL;
    return 0;
}
/****输出****
who and who will get together !
who and who will get together !
************/

程序3.

/*
 *编写程序读入一组string类型的数据,并将它们存储在vector中。接着,把该vector对象复制给一个字符指针数组。
 *为vector中的每个元素创建一个新的字符数组,并把该vector元素的数据复制到相应的字符数组中,
 *最后把指向该数组的指针插入字符指针数组。数组数组内容。
 */
#include <iostream>
#include <cstring>
#include <string>
#include <vector>

using namespace std;

int main()
{
    vector<string> strvec;
    string str;

    cout << "输入字符串" << endl;
    while(cin >> str)
    {
        strvec.push_back(str);
    }
    char **ppChar = new char*[strvec.size()];
    int iTemp = 0;
    for (vector<string>::iterator iter = strvec.begin(); iter != strvec.end(); ++iter,++iTemp)
    {
        char *pTempChar = new char[(*iter).size() + 1];
        //注意将string类字符转成C风格字符;
        strcpy(pTempChar, (*iter).c_str()); 
        ppChar[iTemp] = pTempChar;
    }

    for(int i = 0; i != strvec.size(); ++i)
    {
        cout << (ppChar[i]) << endl;
    }

    for(int i = 0; i != strvec.size(); ++i)
    {
        delete [] ppChar[i];
    }
    delete [] ppChar;
    ppChar=NULL;
    return 0;
}
/****输入****
fretre
rewetr
erwqtf
************/
/****输出****
fretre
rewetr
erwqtf

************/

猜你喜欢

转载自blog.csdn.net/walkerkalr/article/details/81149924