for循环只打印一半的值(使用向量)

waz*_*eer 1 c++ memory vector dynamic

main中的for循环假设pop_back值只打印数组中值的一半.但是,当我写(i <=用户)时,它会打印所有值.

MyVector.h

template<class T>
T MyVector<T>::Pop_back( ){
   return elements_ptr[--vectorSize];
   }
Run Code Online (Sandbox Code Playgroud)

main.cpp中

int main() 
{
    MyVector<int> v1;
    int user = 500;

    for(int i= 1; i <= user; i++){
         v1.Push_back(i);
    }
    cout << v1.size() << endl; // outputs 500

    for (int j = 0; j < v1.size(); j++){
         cout << v1.Pop_back() << " ";
         if( j % 20 ==0 ){
         cout << endl;
         }
   }

   return 0;
 }
Run Code Online (Sandbox Code Playgroud)

5go*_*der 5

问题出在这里:

for (int j = 0; j < v1.size(); j++) { … }
Run Code Online (Sandbox Code Playgroud)

随着你继续从你的矢量中弹出元素,它的报告size()越来越小而且j越来越大.弹出一半元素后,循环条件变为false.

解决方案是使用其中之一

while (v1.size()) { … }
Run Code Online (Sandbox Code Playgroud)

要么

const int N = v1.size();
for (int i = 0; i < N; ++i) { … }
Run Code Online (Sandbox Code Playgroud)

正如你已经发现的那样.我更喜欢前者.