精华内容
下载资源
问答
  • stl vector

    2013-03-06 17:31:36
    // stl-vector.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include using namespace std; void useVector() { vector aa; int num = 0; aa.reserve(11
    // stl-vector.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <iostream>
    #include <vector>
    using namespace std;
    
    void useVector()
    {
    	vector<int> aa;
    	int num = 0;
    	
    	aa.reserve(11); // 事先分配vector容量,否则vector会自动重新分配容量,费时。可以与实际情况相结合写一个算法来分配容量。
    
    	for (int i = 0; i < 12; i++)
    	{
    		aa.push_back(i);
    	}
    
    	cout<<"Size = "<<aa.size()<<endl;  // vector实际大小,含有多少元素
    	cout<<"Max size = "<<aa.max_size()<<endl; // vector可以存储最大元素个数,很大,根据实际情况不同,如机器、系统等
    	cout<<"Capacity = "<<aa.capacity()<<endl; // vector的容量,若果调用reserve分配容量,大小就是你分配的,否则vector会自动分配。根据编译器版本不同,分配规则也不相同
    
    	cout<<aa.at(6)<<endl; 
    	cout<<aa.back()<<endl;  // 最后一个元素,切记与end不同
    	cout<<aa.front()<<endl; // 第一个元素,切记与begin不用,begin与end都是被迭代器调用的,而front与back都是由vector对象调用
    	cout<<"-------------------------"<<endl;
    	
    	aa.insert(aa.begin(), 2);    // 在起始位置插入2
    	aa.insert(aa.begin(), 2, 1); // 在起始位置插入两个1
    	aa.insert(aa.begin(), aa.begin()+2, aa.begin()+4); // 在起始位置插入从aa.begin()+2到aa.begin()+4的元素,不包括aa.begin()+4
    
    	vector<int>::iterator iter;
    
    
    	for (iter = aa.begin(); iter != aa.end(); iter++)
    	{
    		cout<<*iter<<endl;  // 切记不要直接输出迭代器本身
    	}
    
    	vector<int>::reverse_iterator rIter;
    	for (rIter = aa.rbegin(); rIter != aa.rend(); rIter++) // 如果调用rbegin和rend,记得声明一个反向迭代器reverse_iterator
    	{
    		cout<<*rIter<<endl;
    	}
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
    	useVector();
    	return 0;
    }
    

    展开全文
  • STL Vector

    千次阅读 2013-02-14 20:01:50
    We speak of a Vector as a container because it contains other objects. All objects in a container must have the same type. To use a Vector, we must include the appropriate header.

    Introduction


    We speak of a Vector as a container because it contains other objects. All objects in a container must have the same type.

    To use a Vector, we must include the appropriate header.

    #include <vector>

    Using std::vector;

    In the case of  Vector, we must say what type of objects the Vector will contain. We specify the type by putting it between a pair of angle brackets following the template’s name:

    vector<int> ivec;     //ivec holds objects of type int

    vector<Sales_item>   //holds Sales_item


    Defining and Initializing vector


    Table 1.1 Ways to Initialize a vector

      vector<T> v1;

      Vector that holds objects of type T; Default constructor v1 is empty

      vector<T>v2(v1);

      V2 is a copy of v1

      vector<T>v3(n,i);

      V3 has n elements with value i

      vector<T>v4(n);

      V4 has n copies of a value-initialized object

     

    Example:

    vector<int> ivec1;           //ivec1holds objects of type

    vector<int>ivec2(ivec1)      //copy elements of ivec1 into ivec2

    vector<string> svec(ivec1);   //error: svec holds strings, not ints

     

    We can initialize a vector from a count and an element value. The constructor uses the count to determine how many elementsthe vector should have and uses the value to specify the value each of those elements will have:

     

    Example:

    vector<int> ivec4(10,-1)     //10 elements, each initialized to -1

    vector<string> svec(10,”hi!”); //10 strings, each initialized to “hi!”

     


    vector(s) grow dynamically


    A central property of vector(s) is that they are required to be implemented so that it is efficient to add elements to them at run time. Because vector(s) grow efficiently, it is usually best to let the vector grow by adding elements to it dynamically as the element values areknown.

     

    Reason: To support fast random access,vector elements are stored contiguously each element is adjacent to the previous element. Given that element are contiguous, let’s think about what happens when we add an element to a vector: If there is no room in the vector for the new element, it cannot just add an element somewhere else in the memory because the elements must be contiguous for indexing to work. Instead, the vector must allocate new memory to hold the existing elements plus the new one,copy the old elements from the old location into the new space, add the new element,and deallocate the old memory. If vector did this memory allocation and deallocation each time we added an element, then performance would be unacceptably slow.

    The way vector(s) achieve fast allocationis by allocating capacity beyond what is immediately needed. The vector holds this storage in reserve and uses it to allocate new elements as they are added.Thus, there is no need to reallocate the container for each new element.


    Operations on vector(s)


      v.empty()

      Returns true if v is empty; otherwise returns false

      v.size()

      Returns number of elements in v

      v.push_back(t)

      Adds element with value t to the end of v

      v[n]

      Returns element at position n in v

      v1 = v2

      Replaces elements in v1 by a copy of elements in v2

      v1 == v2

      Returns true if v1 and v2 are equal

      !=,<,<=,>,and >=

      Have their normal meanings

     


    The size of a vector


    To use size_type, we must name the type in which it is defined. A vector type always includes the element type of thevector:

     

    Example:

    vector<int> ivec(10);

    for(vector<int>::size_type ix = 0; ix!= ivec.size(); ++ix)

    {

       ivec[ix]= 0;

    }

     


    Adding Elements to a vector


    Use push_back

    Example:

     

    vector<string> text;

    text.push_back(“hello world!”);


      http://www.waitingfy.com/?p=411

     

    展开全文
  • 深入浅析STL vector用法

    2020-09-03 06:20:24
    给大家介绍 stl vector用法,主要知识点在如何恰当的使用它们的成员函数,涉及到条件函数和函数指针在迭代算法中的使用,对stl vector用法感兴趣的朋友可以参考下本
  • STL vector 知识详解

    2010-09-26 03:02:30
    STL vector 知识详解 STL vector 知识详解 STL vector 知识详解 STL vector 知识详解 STL vector 知识详解
  • STL vector使用

    2014-01-01 21:25:55
    STL VECTOR 、迭代器,DEV C++ 编译运行
  • STL Vector 的遍历删除

    2019-04-13 09:18:55
    STL Vector 的遍历删除
                   

    转载自:http://www.cppblog.com/Khan/archive/2009/12/08/102793.html

    Vector 其实就类似动态数组. 事先分配好一定量的内存. 当需要的内存值大于某个阀值. 就重新申请内存. 重新分配. 当小于某个阀值, 也会导致重新分配.(自动收缩部分, stl没有明确规定, 有些库实现了)

    正确: code1
          vector<string> vecFiles;
          vector<string>::iterator  it_pos;
          //@todo 已下载文件过滤
          for (it_pos = vecFiles.begin(); it_pos != vecFiles.end(); ) { 
            string strTmp = *it_pos;
            if( objDownHis.checkHisList( strTmp.c_str() ) ){ //判断是否已下载过, 已下载则从列表删除
              g_Log << TIME << "file:[" << *it_pos << "] found "<< END; //
              vecFiles.erase(it_pos++);
            }else 
              it_pos++;
          }


    正确: code2
          vector<string> vecFiles;
          vector<string>::iterator  it_pos;
          //@todo 已下载文件过滤
          for (it_pos = vecFiles.begin(); it_pos != vecFiles.end(); ) {  
            string strTmp = *it_pos;
            if( objDownHis.checkHisList( strTmp.c_str() ) ){ //判断是否已下载过, 已下载则从列表删除
              g_Log << TIME << "file:[" << *it_pos << "] found "<< END; //
              it_pos = vecFiles.erase(it_pos);
            }else
              it_pos++;
          }

    错误: code3
          vector<string> vecFiles;
          vector<string>::iterator  it_pos;
          //@todo 已下载文件过滤
          for (it_pos = vecFiles.begin(); it_pos != vecFiles.end(); it_pos++) {  
            string strTmp = *it_pos;
            if( objDownHis.checkHisList( strTmp.c_str() ) ){ //判断是否已下载过, 已下载则从列表删除
              g_Log << TIME << "file:[" << *it_pos << "] found "<< END; //
              vecFiles.erase(it_pos);
            }
          }


    code3 错误的原因为, vecFiles.erase(it_pos); 当前的it_pos已经被删除了, 再下一次循环的时候 it_pos++, 访问非法内存..

    然后回过头来看code1, vecFiles.erase(it_pos++); 在当前的it_pos已经被删除的时候, it_pos已经指向下一个位置了. 虽然这里逻辑上是错误的. 但是利用c语法的特性产生了一个正确的结果, 算是一个技巧. 不算是一门技术.

    code2, it_pos = vecFiles.erase(it_pos); erase删除的时候, 也返回了下一个指针的位置,我们将这个位置保留了, 所以这种做法也是正确的.


    另外一个移植性比较好的做法是remove_if 和一个仿函数.

    仿函数可以是:
    struct check {
        check( Object * objDownHis ) : m_obj( objDownHis ) {}
        check( const check & c ) : m_obj( c.m_obj ) {}

        bool operator()(const string & s) const {
           if ( m_obj->checkHisList( s.c_str() ) {
                g_Log .........
                return true;
           }
           return false;
        }
        Object * m_obj;
    };

    vecFiles.erase( std::remove_if( vecFile.begin(), vecFile.end(), check( &objDownHis ) );


    鸣谢p大, lancey, jackz 排名不分先后.. 全按交流时间顺序...

               
    展开全文
  • stl vector resize reserve

    千次阅读 2016-03-15 22:27:58
    stl vector resize reserve

    reserve指容量,resize会调用reserve,之外还会创建对象。

    reserve的操作全是针对内存的,当capacity小于要指定的count时,reserve会reallocate创建内存,但是不会生成对象。

    resize的操作更关心的操作对象。


    打个比方:正在建造的一辆公交车,车里面可以设置40个座椅(reserve(40);),这是它的容量,但并不是说它里面就有了40个座椅,只能说明这部车内部空间大小可以放得下40张座椅而已。而车里面安装了40个座椅(resize(40);),这个时候车里面才真正有了40个座椅,这些座椅就可以使用了。 本例转自该链接


    reserve源码:

    void reserve(size_type _Count)
    {   
        // determine new minimum length of allocated storage
        if (max_size() < _Count)
            _Xlen();    // result too long
        else if (capacity() < _Count)
        {
            // not enough room, reallocate
            pointer _Ptr = this->_Alval.allocate(_Count);
    
    
            _TRY_BEGIN
            _Umove(this->_Myfirst, this->_Mylast, _Ptr);
            _CATCH_ALL
            this->_Alval.deallocate(_Ptr, _Count);
            _RERAISE;
            _CATCH_END
    
    
            size_type _Size = size();
            if (this->_Myfirst != 0)
                {    // destroy and deallocate old array
                _Destroy(this->_Myfirst, this->_Mylast);
                this->_Alval.deallocate(this->_Myfirst,
                    this->_Myend - this->_Myfirst);
                }
    
    
            this->_Orphan_all();
            this->_Myend = _Ptr + _Count;
            this->_Mylast = _Ptr + _Size;
            this->_Myfirst = _Ptr;
        }
    }
    


    resize源码:

    void resize(size_type _Newsize)
    {    
        // determine new length, padding with _Ty() elements as needed
        if (_Newsize < size())
            erase(begin() + _Newsize, end());
        else if (size() < _Newsize)
        {    
            // pad as needed
            _Reserve(_Newsize - size());
            _Uninitialized_default_fill_n(this->_Mylast, _Newsize - size(),
                (_Ty *)0, this->_Alval);
            this->_Mylast += _Newsize - size();
        }
    }
    
    
    void resize(size_type _Newsize, _Ty _Val)
    {   
        // determine new length, padding with _Val elements as needed
        if (size() < _Newsize)
            _Insert_n(end(), _Newsize - size(), _Val);
        else if (_Newsize < size())
            erase(begin() + _Newsize, end());
    }


    展开全文
  • STL vector vs list function comparison: C++ STL TutorialSTL vector vs list function comparison: Function vector listconstructoryesye...
  • STL vector清空的几种方法

    千次阅读 2018-02-02 07:27:34
    STL vector清空
  • C++ STL vector assign用法

    2015-04-10 19:39:35
    C++ STL vector assign用法 C++ STL vector assign用法 assign是重用一个vector,会清除以前的东西;并分配新的内容。
  • STL》— C++ STL vector

    2017-04-08 10:03:48
    C++ STL vector 一、基本操作 (1)头文件#include<vector>. (2)创建vector对象,vector<int> vec; (3)尾部插入数字:vec.push_back(a); (4)使用下标访问元素,cout<<vec[0]<<endl;...
  • STL vector 容器介绍

    2013-07-22 10:13:59
    STL vector 容器介绍 A Presentation of the STL Vector Container (By Nitron) 翻译 masterlee 介绍std::vector,并且讨论它在STL中的算法和条件函数remove_if()。   Download Console Demo - 6.19 Kb Download ...
  • stl vector 函数 C ++ vector :: back()函数 (C++ vector::back() function) vector::back() is a library function of "vector" header, it is used to access the last element from the vector, it returns a ...
  • stl vector 函数 C ++ vector :: capacity()函数 (C++ vector::capacity() function) vector::capacity() is a library function of "vector" header, it is used to find the capacity of a vector, it returns the...
  • stl vector 函数 C ++ vector :: data()函数 (C++ vector::data() function) vector::data() is a library function of "vector" header, it is used to access the vector elements, it returns a pointer to the ...
  • stl vector 函数 C ++ vector :: begin()函数 (C++ vector::begin() function) vector::begin() is a library function of "vector" header, it is used to get the first element of a vector. It returns an ...
  • stl vector 函数 C ++ vector :: front()函数 (C++ vector::front() function) vector::front() is a library function of "vector" header, it is used to access the first element from the vector, it returns a...
  • stl vector 函数 C ++ vector :: size()函数 (C++ vector::size() function) vector::size() is a library function of "vector" header, it is used to get the size of a vector, it returns the total number of ...
  • stl vector 函数 C ++ vector :: at()函数 (C++ vector::at() function) vector::at() is a library function of "vector" header, it is used to access an element from specified position, it accepts a ...
  • stl vector crash 在 deallocator 中

    千次阅读 2013-05-21 16:29:35
    多线程访问stl vector时,会有风险,于是对stl vector做了一层封装,即自己的ThreadVecotr中封装了一个private成员变量是stl vector,对stl vector成员变量的访问都加了锁,这样应该是多线程安全的了。但是,实际上...
  • stl vector 函数 C ++ vector :: empty()函数 (C++ vector::empty() function) vector::empty() is a library function of "vector" header, it is used to check whether a given vector is an empty vector or not...
  • 心希盼 c++ STL Vector

    2010-10-04 09:17:18
    心希盼 c++ STL Vector 类源码 详细说明“心希盼 Vector.doc”
  • stl vector 函数 C ++ vector :: end()函数 (C++ vector::end() function) vector::end() is a library function of "vector" header, it can be used to get the last element of a vector. It returns an iterator...
  • stl vector 函数 C ++ vector :: clear()函数 (C++ vector::clear() function) vector::clear() is a library function of "vector" header, it is used to remove/clear all elements of the vector, it makes the ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 23,259
精华内容 9,303
热门标签
关键字:

stlvector