C++容器操作基础

容器很有用,其实就可以把它当作数组来使用,并且C++的容器封装了很多实用的操作方法,我们可以将它应用在不同的地方。

下面看一个实例,编写代码的平台基于QT应用程序控制台版本,代码如下:

#include <QCoreApplication>
#include <iostream>
#include <iterator>
#include <vector>
#include <cstring>
using namespace std ;

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    //1、vector当作普通数组使用
    vector<int> vec(10);
    for(int i = 0 ; i < 10 ; i++)
        vec[i] = i ;
#if 0
    //(1)、常规写法遍历容器中的元素
    for(int i = 0 ; i < 10 ; i++)
        std::cout << i << ":" << vec[i] << std::endl ;
#endif
    //(2)使用标准vector集中操作的begin()和end()所返回的迭代器
    for(vector<int>::iterator it = vec.begin() ; it != vec.end() ; ++it)
        std::cout << *it << std::endl ;
    std::cout << "========================================" << std::endl ;
    //(3)使用标准vector集中操作的begin()和end()所返回的迭代器====>保证每次都是以const的形式去访问元素,这一种方法比上面那种更好
    for(vector<int>::const_iterator it = vec.begin() ; it != vec.end() ; ++it)
        std::cout << *it << std::endl ;

    //2、当字符串使用  push_back,向vector的后面插入一个元素
    vector<string> str(3);
    str.push_back("hello world");
    str.push_back("123");
    str.push_back("456");
    //用下标迭代访问元素
#if 0
    //(1)、常规遍历容器中的元素
    for(unsigned int i = 0 ; i < str.size() ; i++)
        std::cout << str[i] << std::endl ;
#endif
    //(2)使用标准vector集中操作的begin()和end()所返回的迭代器
    for(vector<string>::iterator count = str.begin() ; count != str.end() ; ++count)
        std::cout << *count << std::endl ;

    //(3)使用标准vector集中操作的begin()和end()所返回的迭代器====>保证每次都是以const的形式去访问元素,这一种方法比上面那种更好
    for(vector<string>::const_iterator count = str.begin() ; count != str.end() ; ++count)
        std::cout << *count << std::endl ;
    return a.exec();
}

运行结果:


猜你喜欢

转载自blog.csdn.net/morixinguan/article/details/80161098