0

I am inserting these elements using the push_back() function, I want to know

How do I print the content of vector 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);

I tried for(int i = 0; i < n; i++) cout << c[i] << endl;

But it gave me this error

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

2 Answers2

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

You need at least C++11.

Also, you can also:

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';
}

But I wouldn't recommend it.

pmaxim98
  • 226
  • 2
  • 7
0

whenever you see the following sign << used to print stuff out, it works because its overloaded; however vector<> does not have an overload function to able you to do this. what you can do is the following:

1- there is a iterarot class that allows you to iterate in containers such as vector:

vector<int>::iterator it;

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

cout << endl;

2- if you are writing your class, write an overload function like so:

to iterate:

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

overload func:

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

  }

here is how to use vector and 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;
BlooB
  • 955
  • 10
  • 23