print vector c++ code example

Example 1: cpp print vector

for(int i = 0; i < vec.size(); i++)
    std::cout << vec[i] << ' ';

Example 2: c++ print elements of vector to the console

#include <iostream>
#include <vector>

int main()
{
	std::vector<int> myVector = {1, 2, 3, 4, 5, 6};

	for(int i = 0; i < myVector.size(); i++)
	{
		std::cout << myVector[i] << std::endl;
        
        //***** alternate method *******
		//std::cout << myVector.at(i) << std::endl;		
	}	
}

Example 3: print matrix c++

#include <iostream>

using namespace std;

int matrix[3][3];

int main()
{
    // asigning values, I suppose this is done allready.

    for(int x=0;x<3;x++)
    {
        for(int y=0;y<3;y++)
        {
            matrix[x][y]=1;
        }
    }

    // showing the matrix on the screen

    for(int x=0;x<3;x++)  // loop 3 times for three lines
    {
        for(int y=0;y<3;y++)  // loop for the three elements on the line
        {
            cout<<matrix[x][y];  // display the current element out of the array
        }
    cout<<endl;  // when the inner loop is done, go to a new line
    }
    return 0;  // return 0 to the OS.
}

Example 4: print a 3d vector in c++

// A recursive function able to print a vector
// of an arbitrary amount of dimensions.
template<typename T>
static void show(T vec)
{
  std::cout << vec;
}


template<typename T>
static void show(std::vector<T> vec)
{
  int size = vec.size();
  if (size <= 0) {
    std::cout << "invalid vector";
    return;
  }
  std::cout << '{';
  for (int l = 0; l < size - 1; l++) {
    show(vec[l]);
    std::cout << ',';
  }
  show(vec[size - 1]);
  std::cout << '}';
}

Tags:

Cpp Example