注册 登录
编程论坛 C++教室

[讨论]关于STL的问题

热情依然 发布于 2007-09-09 18:09, 635 次点击
由于想更加好的运用STL 和重新认识数据结构,最近我在看SGI 的STL源代码,看到vector的实现方法的时候,发现了个问题 那就是 填充元素的两个函数  unitialize_fill 和 fill ,看了MSDN之后,还是不能区别两个函数有什么区别,事实上,我将里面的代码抽出来,将本来unitialize_fill 的地方换成 fill,都是正常的运行,请问,这两个函数有什么本质的区别?是否新动态分配的内存,用unitialize_fill 填充会快点??
9 回复
#2
aipb20072007-09-09 22:33
fill函数我就知道,

unitialize_fill有吗?查不到啊!
#3
yuyunliuhen2007-09-09 22:37

我也没听说过这个

#4
热情依然2007-09-09 22:50

uninitialized_fill 不好意思,打快了,少了个d
MSDN 是这样说的 Copies objects of a specified value into an uninitialized destination range.
从这里我完全看不出跟fill有什么区别,难道如果内存上还没有初始值,用这个会快一些?

[此贴子已经被作者于2007-9-9 22:52:50编辑过]

#5
yuyunliuhen2007-09-09 23:14

有的有的,再细看一下代码还是可以发现的
fill:Assigns the same new value to every element in a specified rangeThe destination range must be valid; all pointers must be dereferenceable, and the last position is reachable from the first by incrementation. The complexity is linear with the size of the range.


uninitialized_fill :Copies objects of a specified value into an uninitialized destination range.This algorithm allows the decoupling of memory allocation from object construction.



#6
duffebear2007-09-09 23:18
都是高手,我才刚刚开始学习sgi stl源码剖析
#7
aipb20072007-09-09 23:35
to yuyun:

举个ex说说
#8
热情依然2007-09-09 23:50

我知道了,unitialized_fill 里面为元素赋值的时候,是用
template<class T1,class T2>
inline void construct(T1 *p, const T2& value){
new (p) T1(value);
}
这样就不需要元素提领,只要地址合法就可以了感谢

#9
yuyunliuhen2007-09-09 23:54

MSDN上的例子很好了,我就采取“拿来主义”了
// memory_uninit_fill.cpp
// compile with: /EHsc
#include <memory>
#include <iostream>

using namespace std;

class Integer { // No default constructor
public:
Integer( int x ) : val( x ) {}
int get( ) { return val; }
private:
int val;
};

int main( )
{
const int N = 10;
Integer val ( 25 );
Integer* Array = ( Integer* ) malloc( N * sizeof( int ) );
uninitialized_fill( Array, Array + N, val );
int i;
cout << "The initialized Array contains: ";
for ( i = 0 ; i < N; i++ )
{
cout << Array [ i ].get( ) << " ";
}
cout << endl;
}

output:
The initialized Array contains: 25 25 25 25 25 25 25 25 25 25
/////////////////////////////////////////////////////////////////


// alg_fill.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <iostream>

int main( )
{
using namespace std;
vector <int> v1;
vector <int>::iterator Iter1;

int i;
for ( i = 0 ; i <= 9 ; i++ )
{
v1.push_back( 5 * i );
}

cout << "Vector v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;

// Fill the last 5 positions with a value of 2
fill( v1.begin( ) + 5, v1.end( ), 2 );

cout << "Modified v1 = ( " ;
for ( Iter1 = v1.begin( ) ; Iter1 != v1.end( ) ; Iter1++ )
cout << *Iter1 << " ";
cout << ")" << endl;
}
output:
Vector v1 = ( 0 5 10 15 20 25 30 35 40 45 )
Modified v1 = ( 0 5 10 15 20 2 2 2 2 2 )

#10
aipb20072007-09-10 00:00
明天看,睡觉了!
1