打印矢量值

时间:2017-08-16 13:12:13

标签: c++ vector

我使用push_back()函数插入这些元素,我想知道

如何打印矢量c的内容?

vector<int> c[2];
c[0].push_back(0);
c[0].push_back(1);
c[1].push_back(2);
c[0].push_back(3);

我尝试了for(int i = 0; i < n; i++) cout << c[i] << endl;

但它给了我这个错误

error: no match for 'operator<<' in 'std::cout << c[i]'|

2 个答案:

答案 0 :(得分:1)

  for (const auto & vec : c) {
        for (const auto elem : vec)
            std::cout << elem << ' ';
        std::cout << '\n';
    }

至少需要C ++ 11。

另外,您还可以:

constexpr size_t vecLen = 2;
std::vector<int> c[vecLen];
c[0].push_back(0);
c[0].push_back(1);
c[1].push_back(2);
c[0].push_back(3);

for (size_t vecIndex = 0; vecIndex < vecLen; ++vecIndex) {
    for (size_t itemIndex = 0; itemIndex < c[vecIndex].size(); ++itemIndex)
        std::cout << c[vecIndex][itemIndex] << ' ';
    std::cout << '\n';
}

但我不推荐它。

答案 1 :(得分:0)

每当您看到以下用于打印输出的符号<<时,它就会起作用,因为它超载了;但是vector<>没有过载功能可以让你这样做。你能做的是以下几点:

1-有一个iterarot类,允许您迭代容器,例如vector:

vector<int>::iterator it;

cout << "myvector contains:";
for ( it=myvector.begin() ; it < myvector.end(); it++ )
    cout << " " << *it;

cout << endl;

2-如果你正在写你的课,写一个像这样的重载函数:

iterate

std::vector<int>::const_iterator iter= vec.begin();
for(iter; iter != vec.end(); ++iter)
  {
     cout<<*iter; //This is what step 2 provides for
  }

重载功能:

ostream& operator<<( ostream& os, const vector<int>&)
  {

  }

这里是如何使用vector和iterator:

    cout << "vector from initializer list: " << endl;
    vector<int> vi1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    cout << "size: " << vi1.size() << endl;
    cout << "front: " << vi1.front() << endl;
    cout << "back: " << vi1.back() << endl;

    // iterator
    vector<int>::iterator itbegin = vi1.begin();
    vector<int>::iterator itend = vi1.end();
    for (auto it = itbegin; it < itend; ++it) {
        cout << *it << ' ';
    }
    cout << endl;

    cout << "element at 5: " << vi1[5] << endl;
    cout << "element at 5: " << vi1.at(5) << endl;

    cout << "range-based for loop:" << endl;
    for (int & i : vi1) {
        cout << i << ' ';
    }
    cout << endl;