在C++中显示向量容器的内容

hea*_*ser 9 c++ stl vector

以下是使用STL向量容器的C++程序.只是想知道为什么display()函数没有将矢量内容打印到屏幕上.如果显示size()行被注释掉,则display()函数可以正常工作.

#include <iostream>
#include <vector>

using namespace std;

void display(vector<int> &v)
{
    for(int i; i<v.size(); i++)
    {
        cout << v[i] << " ";
    }
    cout << "\n" << endl;
}

int main()
{
    vector<int> v;
    cout << "Size of Vector=" << v.size() << endl;

    //Putting values into the vector
    int x;
    cout << "Enter five integer values" << endl;
    for(int i; i<5; i++)
    {
        cin >> x;
        v.push_back(x);
    }
    //Size after adding values
    cout << "Size of Vector=" << v.size() << endl;

    //Display the contents of vector
    display(v);

    v.push_back(6);

    //Size after adding values
    cout << "Size of Vector=" << v.size() << endl;

    //Display the contents of vector
    display(v);

}
Run Code Online (Sandbox Code Playgroud)

输出:

Size of Vector=0

Enter five integer values

1

2

3

4

5

Size of Vector=5


Size of Vector=6
Run Code Online (Sandbox Code Playgroud)

111*_*111 27

有一种用于打印矢量的惯用方法.

#include <algorithm>
#include <iterator>

//note the const
void display_vector(const vector<int> &v)
{
    std::copy(v.begin(), v.end(),
        std::ostream_iterator<int>(std::cout, " "));
}
Run Code Online (Sandbox Code Playgroud)

这种方式是安全的,不需要您跟踪矢量大小或类似的东西.它也很容易被其他C++开发人员识别.

此方法也适用于其他容器类型,不允许随机访问.

std::list<int> l;
//use l

std::copy(l.begin(), l.end(),
          std::ostream_iterator<int>(std::cout, " "));
Run Code Online (Sandbox Code Playgroud)

这与输入的两种方式也考虑以下:

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

int main()
{
    std::cout << "Enter int end with q" << std::endl;
    std::vector<int> v; //a deque is probably better TBH
    std::copy(std::istream_iterator<int>(std::cin),
              std::istream_iterator<int>(),
              std::back_inserter<int>(v));

    std::copy(v.begin(), v.end(),
              std::ostream_iterator<int>(std::cout, " "));
}
Run Code Online (Sandbox Code Playgroud)

此版本不需要任何硬编码大小或手动管理实际元素.


YXD*_*YXD 8

您没有初始化变量.for(int i = 0;for(int i;