我试图存储一些每次都会改变的元素,但我不知道哪个
方式更好,为什么.我正在考虑两种方式,1)声明int和loop或者数组
使用矢量.
哪种方式更好,为什么?
声明int的数组是否有任何未来的memore问题作为泄漏?
下面的代码显示了我正在谈论的两种方式:
1)
#include <iostream>
#include <vector>
int main()
{
int x[5];
x[0] = 10;
x[1] = 20;
x[2] = 30;
x[3] = 40;
x[4] = 50;
for(unsigned int i = 0;i<=sizeof(x[5]); i++)
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
2)
#include <iostream>
#include <vector>
int main()
{
std::vector<int> x;
x.push_back(10);
x.push_back(20);
x.push_back(30);
x.push_back(40);
x.push_back(50);
for(unsigned int i = 0;i<=x.size()-1; i++)
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果这就是你要做的全部,并且你的数组总是具有编译时已知的大小,那么你就不需要了std::vector.
另一方面,在C++ 11中,您可以使用std::array而不是普通的C数组(std::array在C数组上是零开销,更安全且功能更强的包装器):
#include <iostream>
#include <array>
int main()
{
std::array<int, 5> x = { 10, 20, 30, 40, 50 };
for (unsigned int i = 0; i < x.size(); i++)
// ^^^^^^^^
{
std:: cout << "x[" << i << "] = "<< x[i] << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.注意,它std::array提供了一个size()您可能想要使用的成员函数而不是sizeof运算符.
此外,由于std::array是一个标准的序列容器,你可以这样迭代它的元素:
std::size_t i = 0;
for (auto e : x)
{
std:: cout << "x[" << i++ << "] = "<< e << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
这是一个实例.
如果在编译时已知大小,请使用std::array.如果没有,请使用std::vector.在任何一种情况下,使用迭代器来查看元素:
typedef std::array<int> my_container_type;
typedef my_container::iterator iterator;
my_container_type my_container = { whatever };
for (iterator it = my_container.begin(); it != my_container.end(); ++it)
std::cout << "x[" << (it - my_container.begin()) << "] = " << *it << '\n';
Run Code Online (Sandbox Code Playgroud)
通过使用迭代器,您可以大大降低意外使用循环限制的风险sizeof(x[5]),这是无意义的.
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |