zoukankan      html  css  js  c++  java
  • 【C++基础学习】Vector

    代码练习:

    #include <iostream>
    #include <vector>
    using namespace std;
    
    int main(){
        cout << "****vector exercise****" << endl;
        vector<int>vec(9, 8);
        cout << "vec原值为:" << endl;
        //编写9个元素的vector对象,用迭代器把每个元素值改为当前值+1
        int i=0;
        for (vector<int>::iterator iter = vec.begin(); iter != vec.end();iter++)
        {
            cout << *iter << " ";
            *iter = (*iter)+(++i);
        }
    
        //对于数据时只读操作,可以使用const_iterator
        cout <<endl<< "vec改后值为:" << endl;
        for (vector<int>::const_iterator citer = vec.begin(); citer != vec.end(); citer++)
        {
            cout << *citer << " ";
        }
    
        //求vec的中值
        vector<int>::iterator min = vec.begin() + vec.size() / 2;
        //vector<int>::iterator min = vec.begin() +vec.size()/2;
        cout <<endl<<"vec的中值为:";
        cout << *min << endl;
    
        system("pause");
        return 0;
    }

    程序运行结果如下:

    在上述代码中用到了两个iterator,一个是iterator,另一个是const_iterator,其中const_iterator是一个只读的迭代器。

    当然还有一个是const iterator ,这个也可以,不过不能指定指定位置,所以很少使用。

    *iter 是读取vec的当前值。    *操作符为解引用操作符。

    值得一看的还有最下面的求iver的中间值。

    vector<int>::iterator min = vec.begin() +vec.size()/2;

    可以思考下,如果改为 vector<int>::iterator min =( vec.begin() +vec.size() )/2;    

    那么结果会是什么样的呢?

    vs2013 会产生如下的报错信息:

  • 相关阅读:
    使用 libevent 和 libev 提高网络应用性能
    An existing connection was forcibly closed by the remote host
    各种浏览器的兼容css
    vs输出窗口,显示build的时间
    sass
    网站设置404错误页
    List of content management systems
    css footer not displaying at the bottom of the page
    强制刷新css
    sp_executesql invalid object name
  • 原文地址:https://www.cnblogs.com/lou424/p/5012165.html
Copyright © 2011-2022 走看看