简体   繁体   English

在cout语句中连接数组大小

[英]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: 我正在尝试输出数组中元素对象的数量,但是其语法与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? 如果.size在C ++语法中不起作用,怎么办?

The C++ equivalent of a Java array is std::vector . Java数组的C ++等效项是std::vector sent.size() is the correct way to get the size. sent.size()是获取大小的正确方法。

You didn't post your definition of sent but it should be std::vector<YourObject> sent; 您没有发布sent的定义,但是应该将其定义为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++. 我猜想您尝试使用C样式数组-请勿这样做,由于历史原因,C样式数组具有奇怪的语法和行为,实际上根本不需要在C ++中使用它们。

If your array is a C-Array, you can loop through it like this: 如果您的阵列是C阵列,则可以像这样遍历它:

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

... where TYPE is the underlying type of the array. ... TYPE是数组的基础类型。

For example, if sent is defined as: 例如,如果发送定义为:

int sent[];

... then TYPE would be int , like this: ...那么TYPE将是int ,就像这样:

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

A C-Array is not an object. C数组不是对象。 So it has no members or methods and you cannot use the member operator with it. 因此,它没有成员或方法,并且您不能将member运算符与其一起使用。 The sizeof operator is used to find the size of a fundamental type, in bytes. sizeof运算符用于查找基本类型的大小(以字节为单位)。 sizeof returns an integer value of type size_t . sizeof返回类型为size_t的整数值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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