P*******b 发帖数: 1001 | 1 what problem does the following code have?
vector vec4;
vec4.reserve(10);
fill_n(vec4.begin(), 10, 1);
copy(vec4.begin(), vec4.end(), ostream_iterator(cout, " "));
cout << endl; | s*********t 发帖数: 1663 | 2 vec4没初始化?
【在 P*******b 的大作中提到】 : what problem does the following code have? : vector vec4; : vec4.reserve(10); : fill_n(vec4.begin(), 10, 1); : copy(vec4.begin(), vec4.end(), ostream_iterator(cout, " ")); : cout << endl;
| h***9 发帖数: 45 | 3 //This seems to work
//The problem seems to be in vec4.reserve(10).
#include
#include
#include
#include
using namespace std;
int main(){
vector vec4 (10,0); // myvector: 10 10 10 10 10 10 10 10
// vec4.reserve(10);
fill_n(vec4.begin(), 10, 1);
copy(vec4.begin(), vec4.end(), ostream_iterator (cout, " "));
cout << endl;
return 0;
}
【在 P*******b 的大作中提到】 : what problem does the following code have? : vector vec4; : vec4.reserve(10); : fill_n(vec4.begin(), 10, 1); : copy(vec4.begin(), vec4.end(), ostream_iterator(cout, " ")); : cout << endl;
| h***9 发帖数: 45 | 4 Actually the problem is in fill_n
fill_n is defined as:
template < class OutputIterator, class Size, class T >
void fill_n ( OutputIterator first, Size n, const T& value )
{
for (; n>0; --n) *first++ = value;
}
Note that the first parameter is defined as an OutputIterator.
So if a vector has length 0, even if it has a larger capacity, fill_n will
not do anything.
【在 h***9 的大作中提到】 : //This seems to work : //The problem seems to be in vec4.reserve(10). : #include : #include : #include : #include : using namespace std; : int main(){ : vector vec4 (10,0); // myvector: 10 10 10 10 10 10 10 10 : // vec4.reserve(10);
| P*******b 发帖数: 1001 | 5 正解,牛人。
【在 h***9 的大作中提到】 : Actually the problem is in fill_n : fill_n is defined as: : template < class OutputIterator, class Size, class T > : void fill_n ( OutputIterator first, Size n, const T& value ) : { : for (; n>0; --n) *first++ = value; : } : Note that the first parameter is defined as an OutputIterator. : So if a vector has length 0, even if it has a larger capacity, fill_n will : not do anything.
| i**r 发帖数: 40 | 6 fill and fill_n are for assignments.
if size() == 0, use an inserter:
fill_n(back_inserter(vec4), 10, 1); | P*******b 发帖数: 1001 | 7 我只是觉得至少应该抱个runtime error
【在 i**r 的大作中提到】 : fill and fill_n are for assignments. : if size() == 0, use an inserter: : fill_n(back_inserter(vec4), 10, 1);
| z****e 发帖数: 2024 | 8 undefined behavior doesn't mean runtime error.
you need to see the definition of vector::reserve.
【在 P*******b 的大作中提到】 : 我只是觉得至少应该抱个runtime error
|
|