c++ - C++ 中的 vector : Why i'm getting so much errors for this simple copy & print program?

标签 c++ c++11 vector stl iteration

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

一件事是我选择了两种方法来首先使用 vec.begin() 进行此迭代; vec.end() 方法 & 另一个是 for (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;

}

最佳答案

有几项可能的改进。

您将迭代器与索引混淆了。一个迭代器 it是指向 vector 的美化指针,您需要通过键入 *it 来取消引用.索引i是 vector 开头的偏移量,表示 vecList[i]会给你那个元素。

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

你需要循环到vecList.size() . vector 的容量是为 vector 容器的元素分配的存储空间的大小。循环最好使用范围 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;

}

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

关于c++ - C++ 中的 vector : Why i'm getting so much errors for this simple copy & print program?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11982058/

相关文章:

c++ - 什么逻辑与操作与流输出有关?

c++ - 将标准元组解包为指针?

c++ - 我想创建一个 Vector 来保存类

c++ - C++ 中 std::vector 的基本问题

c++ - 多级继承

c++ - 数组溢出 C++(在 arr[0])?

c++ - 为什么标准允许我在没有析构函数的情况下自由存储分配类?

list - 将列表和向量压缩在一起,无需重复遍历

c++ - 为什么 SendInput() 不工作?

c++ - C++中int*和char*的区别