C++中的向量:为什么我这个简单的复制和打印程序会出现这么多错误?

T0M*_*FeR 3 c++ iteration stl vector c++11

我正在尝试使用算法lib和vector lib首先将一组数字从一个数组复制到一个向量中,然后使用迭代打印它,我的代码问题在哪里?

有一件事是我首先使用vec.begin()选择2种方式进行迭代; vec.end()方法和另一个方法是(i = 0; i <vec.capacity(); i ++)都面临错误.

我该怎么办?

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    int intArray[] = {5,6,8,3,40,36,98,29,75};

    vector<int> vecList(9);
    //vector<int>::iterator it;
    copy (intArray, intArray+9,vecList);
    //for(it  = vecList.begin() ; it != vecList.end() ; it++)
    for (int it = 0 ; it < vecList.capacity() ; it++)
    {
        cout<<*it<<endl;
     }

    system("pause");
    return 0;

}
Run Code Online (Sandbox Code Playgroud)

Tem*_*Rex 7

有几种改进可能.

您将迭代器与索引混淆.迭代器it是指向矢量的美化指针,您需要通过键入来解除反射*it.索引i是从向量开头的偏移量,并且说明vecList[i]将给出该元素.

矢量的初始化最好使用初始化列表(C++ 11)完成,而不是从数组中读取.

你需要循环到vecList.size().向量的容量是向量容器的元素的已分配存储空间的大小.循环最好用一个ranged-for循环来表示Kerrek SB,或者一个std::for_each+一个lambda表达式,或者像你一样循环for循环.然而,在这种情况下,最好养成做it != vecList.end()(而不是使用<)和做++it而不是做的习惯it++.

请注意,我还习惯于auto避免编写显式迭代器类型.auto在任何地方使用它也是一个好习惯.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
    // initialize vector with a list of elements
    vector<int> vecList {5,6,8,3,40,36,98,29,75}; 

    // loop from begin() to end() of vector, doing ++it instead of it++ 
    for (auto it = vecList.begin(); it != vecList.end(); ++it) 
    {
        cout<<*it<<endl;
    }

    // the pause command is better done by setting a breakpoint in a debugger

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

Ideone上的输出(这使用g ++ 4.5.1编译器,最好升级到至少该版本以利用C++ 11特性).


Luc*_*ore 6

问题是您混淆了索引和迭代器.

w/index:

 for (int i = 0  ; i < vecList.size() ; it++)
 {
    cout<<vecList[i]<<endl;
 }
Run Code Online (Sandbox Code Playgroud)

w /迭代器

 for (std::vector<int>::const_iterator it = vecList.begin()  ; i != vecList.end() ; it++)
 {
    cout<<*it<<endl;
 }
Run Code Online (Sandbox Code Playgroud)