Array Size Concatenation

How do I concatenate the size (amount of elements) of an array in a cout statement with c++?

1
2
3
4
5
6
7
8
9
10
11
  // print list of all messages to the console
void viewInbox()
{
	cout << "You have " << inbox.size() << " new messages.\n";//Error: left of '.size' must have class/struct,union
	std::cout << "Index      Subject" << '\n';

	for (size_t i = 0; i < inbox.size(); ++i)
	{
		std::cout << i << "    : " << inbox[i].getSubject() << '\n';
	}
}
C++ arrays do not have member functions. You will want to use a vector:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <vector>
#include <iostream>

void print( const std::vector< int >& vect )
{
  for ( std::vector< int >::size_type i = 0; i < vect.size() ; ++i )
    std::cout << vect[i] << '\n';
}

int main( void )
{
  std::vector< int > ints = { 4, 3, 2, 1 };
  ints.push_back( 5 );
  print( ints );
}


If you can't use a vector and you have declared your array using braces, you can take advantage of sizeof

1
2
int arr[] = { 1, 2, 3, 4, 5 };
size_t arr_size = sizeof( arr ) / sizeof( arr[0] );
If the OP really wants an array, C++11 provides a wrapper for the built-in array, std::array( from my guess in his code, no push_backs needed from print ). Using std::array<T> is very similar to using the built-in array has no effect on their run-time performance, with much more features.

Unlike with the other containers in the Standard Library, swapping two array containers is a linear operation that involves swapping all the elements in the ranges individually, which generally is a considerably less efficient operation. On the other side, this allows the iterators to elements in both containers to keep their original container association.

Another unique feature of array containers is that they can be treated as tuple objects: The <array> header overloads the get function to access the elements of the array as if it was a tuple, as well as specialized tuple_size and tuple_element types.
Topic archived. No new replies allowed.