简体   繁体   中英

Concatenating an array size in cout statement

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?

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++.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM