我有一个大小的字符串数组5,我有n元素.我怎么能确定n?我试过sizeof(array)/sizeof(array[0]),但是返回数组的大小,即5.我的代码是:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string array[5];
array[0] = "pie";
array[1] = ":P";
array[2] = "YELLOW";
cout << sizeof(array)/sizeof(array[0]);
}
Run Code Online (Sandbox Code Playgroud)
我有一个大小的字符串数组
5,我有n元素.我怎么能确定n?
n是5.你的数组有5个元素,因为你声明它是一个包含5个字符串的数组.array[3]并且array[4]只是空字符串(""),但它们仍然存在,并且是完全有效的元素.
如果你想计算你的数组有多少非空字符串,你可以使用例如std::count_iflambda:
int numberOfNonEmptyStrings = count_if(begin(array), end(array),
[](string const& s) { return !s.empty(); });
Run Code Online (Sandbox Code Playgroud)
或手工制作的循环:
int numberOfNonEmptyStrings = 0;
for (auto const& s : array)
if (!s.empty())
++numberOfNonEmptyStrings;
Run Code Online (Sandbox Code Playgroud)
内置数组(称为原始数组)不支持动态长度.它有一个固定的长度.对于声明的数组,可以通过多种方式找到固定长度,包括您使用的非常安全的C语言.
std::vector<>标准库(标题<vector>)中的Itemtype管理原始数组和动态长度.而这显然正是你所需要的.内部数组(称为矢量"缓冲区")会根据需要自动替换为较大的数组,因此您甚至不需要预先指定容量 - 您只需向向量添加项目即可.
向向量添加项通常是通过调用的方法完成的push_back,查找当前项的数量(长度)通常是通过size方法完成的,如下所示:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> a;
a.push_back( "pie" );
a.push_back( ":P" );
a.push_back( "YELLOW" );
cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)
但由于std::vector支持通过大括号初始化列表进行初始化,因此您不必使用push_back已知的初始项:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> a = { "pie", ":P", "YELLOW" };
cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)
const如果不打算改变该向量,则使用最后的改进.这使得更容易推理代码.随着const你看前面那个没有下面所有的代码将改变这个矢量,所以可以肯定的什么值它提供了在任何时候:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> const a = { "pie", ":P", "YELLOW" };
cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)
免责声明:编译器脏手无法触及代码.
如果你真的想要一个固定大小的数组,最好使用std::array<Itemtype>.它适用于基于范围的循环.它有一个size方法,像矢量,所以你可以做这样的事情:
#include <algorithm> // std::count
#include <iostream>
#include <string> // std::string
#include <array> // std::array
using namespace std;
int main()
{
array<string, 5> const a = { "pie", ":P", "YELLOW" };
cout << "Fixed size: " << a.size() << endl;
int const n_empty = count( begin( a ), end( a ), "" );
cout << "Non-empty strings: " << a.size() - n_empty << endl;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
120 次 |
| 最近记录: |