0

I'm trying to output the number of element-objects in my array, but the syntax for that is not the same as it is for Java:

    // print list of all messages to the console
void viewSent()
{
    cout << "You have " << sent.size() << " new messages.\n";//Error: left of '.size' must have class/struct,union
    std::cout << "Index      Subject" << '\n';

    for (size_t i = 0; i < sent.size(); ++i)
    {
        std::cout << i << "    : " << sent[i].getSubject() << '\n';
    }
}

if the .size doesn't work in C++ syntax, what does?

2 Answers2

4

The C++ equivalent of a Java array is std::vector. sent.size() is the correct way to get the size.

You didn't post your definition of sent but it should be std::vector<YourObject> sent;, perhaps with initial size and/or values also specified.

I'm guessing you tried to use a C-style array -- don't do that, C-style arrays have strange syntax and behaviour for historical reasons and there is really no need to use them ever in C++.

M.M
  • 138,810
  • 21
  • 208
  • 365
  • I know vectors are better, but right now, I need the C-style array version of .size() Anybody know? – SamJava_The_Hut Sep 27 '14 at 02:54
  • @SamJava_The_Hut So it is not a vector? Can you post your definition of `sent`? – Deqing Sep 27 '14 at 03:32
  • There is no C-style array version of `size()`. [See here](http://stackoverflow.com/questions/15861115/how-to-find-out-the-length-of-an-array) for some ideas. – M.M Sep 27 '14 at 03:39
  • Deqing, the gory details of the sent definition can be found in the code at http://stackoverflow.com/questions/26071083/expression-must-have-class-type-with-array-concatination – SamJava_The_Hut Sep 27 '14 at 03:46
0

If your array is a C-Array, you can loop through it like this:

for (size_t i = 0; i < (sizeof(sent) / sizeof(TYPE)); ++i)

... where TYPE is the underlying type of the array.

For example, if sent is defined as:

int sent[];

... then TYPE would be int, like this:

for (size_t i = 0; i < (sizeof(sent) / sizeof(int)); ++i)

A C-Array is not an object. So it has no members or methods and you cannot use the member operator with it. The sizeof operator is used to find the size of a fundamental type, in bytes. sizeof returns an integer value of type size_t.

Bill Weinman
  • 2,036
  • 2
  • 17
  • 12