首页 > 解决方案 > 获取地图数组的长度

问题描述

我有这样的事情:

#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};

标签: c++

解决方案


当您将数组作为参数传递给函数时,它会衰减为指针,因此,您不能在其上使用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>?为什么是“使用命名空间标准;被认为是不好的做法?以获得良好的编码指南。


推荐阅读