获取地图数组的长度

时间:2020-04-06 01:34:56

标签: c++

我有这样的东西:

<?php
echo exec('"C:\Program Files (x86)\Microsoft Visual Studio\VB98\VB6.EXE" /MAKE D:\Websites\devopservices\dlledit\portaleeditorisen\NewSecurity\Data\NewSecurity_Data.vbp D:\Websites\devopservices\dlledit\compiled\NewSecurity_Data.dll');
?>

现在,我没有在#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的数组大小时,我得到0,这是不对的。

如何获得这个特殊数组的正确长度?

processes

1 个答案:

答案 0 :(得分:4)

当将数组作为参数传递给函数时,它decays into a pointer,因此,您不能在其上使用sizeof(processes)/sizeof(*processes)范式/方法。

>

您应该使用std::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;
}

此外,请参见以下内容:Why should I not #include <bits/stdc++.h>?Why is "using namespace std;" considered bad practice?,以获取良好的编码准则。