c++ - 获取地图数组的长度
问题描述
我有这样的事情:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
void shortestRemainingTime(map<string, string> processes[]){
int size = (sizeof(processes)/sizeof(*processes));
cout << size;
}
int main() {
map<string, string> process { { "name", "open paint" }, { "remainingTime", "1000" } };
map<string, string> process2{ { "name", "open photoshop" }, { "remainingTime", "500" } };
map<string, string> process3{ { "name", "open word" }, { "remainingTime", "600" } };
map<string, string> processes[] = {process, process2, process3};
shortestRemainingTime(processes);
return 0;
}
现在,我没有进行任何计算,shortestRemainingTime
但是当我打印 map 数组的大小时processes
,我得到 0,这是不正确的。
我怎样才能得到这个特殊数组的正确长度?
map<string, string> processes[] = {process, process2, process3};
解决方案
当您将数组作为参数传递给函数时,它会衰减为指针,因此,您不能在其上使用sizeof(processes)/sizeof(*processes)
范例/方法。
您应该使用 astd::vector
代替您的数组,在这种情况下,您可以使用它的size()
功能。这是您的代码的一个版本,它可以做到这一点:
#include <iostream>
#include <map>
#include <vector>
#include <string>
using std::cout;
using std::vector;
using std::map;
using std::string;
// Note: Passing the vector by reference avoids having to copy a (potentially)
// large object. Remove the "const" qualifier if you want the function to modify
// anything in the vector...
void shortestRemainingTime(const vector<map<string, string>> &processes)
{
size_t size = processes.size();
cout << size;
}
int main()
{
map<string, string> process{ { "name", "open paint" }, { "remainingTime", "1000" } };
map<string, string> process2{ { "name", "open photoshop" }, { "remainingTime", "500" } };
map<string, string> process3{ { "name", "open word" }, { "remainingTime", "600" } };
vector<map<string, string>> processes = { process, process2, process3 };
shortestRemainingTime(processes);
return 0;
}
另外,请参阅以下内容:为什么我不应该#include <bits/stdc++.h>?为什么是“使用命名空间标准; ” 被认为是不好的做法?以获得良好的编码指南。
推荐阅读
- reactjs - 无法在反应中获取
- mips - MIPS 如何直接从文本段中读取。(火星模拟器)
- angular - Angular 10 中未显示验证消息
- c# - 如何计算学生在班级中每个学科的位置?
- asp.net-core - Razor Pages .Net Core - 将 ID 从表格行传递到模式弹出窗口
- c - C 程序如何显示最大可能 unsigned long long 的值?
- c# - 如何将 0x53797374656d2e427974655b5d 转换为图像格式并使用 asp 处理程序显示 tnem
- django - 两个不同的模型在管理页面 django 中具有相同的名称
- python - 使用python降低相机的FPS
- python - python输出带有时间戳的未捕获异常堆栈跟踪