如何将向量大小与整数进行比较? [英] How compare vector size with an integer?

查看:84
本文介绍了如何将向量大小与整数进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果vector的大小(声明为 vector< int> vectorX )与预期的大小不同,我正在使用以下代码引发错误.

I am using the following code to throw an error if the size of vector (declared as vector<int> vectorX) is is different than intended.

vector<int> vectorX;
int intendedSize = 10;
// Some stuff here
if((int)(vectorX.size()) != (intendedSize)) {
    cout << "\n Error! mismatch between vectorX "<<vectorX.size()<<" and intendedSize "<<intendedSize;
    exit(1);
}

cout 语句显示的大小相同.比较未显示它们相等.

The cout statement shows the same size for both. The comparison is not showing them to be equal.

输出为错误!vectorX 10与预期大小10之间不匹配

错误在哪里?之前我尝试过(unsigned int)(intendedSize),但这也表明它们不相等.

Where is the error? Earlier I tried (unsigned int)(intendedSize) but that too showed them unequal.

推荐答案

if语句右侧缺少)

if((int)(vectorX.size()) != (intendedSize)) {
                                          ^^^
}

但是请注意,将std :: vector :: size的返回值转换为int很不好.您将失去大小可能的一半(感谢chris).

But note, it's bad to cast return value of std::vector::size to int. You lose half of the possibilities of what the size could be(thanks to chris).

您应该写:

size_t intendedSize = 10; 
// OR unsign int intendedSize  = 10; 
if(vectorX.size() != intendedSize) {
}

这篇关于如何将向量大小与整数进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆