【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
我可以创建一个数组并像这样初始化它:
int a[] = {10, 20, 30};
如何创建一个std::vector
并初始化它同样优雅?
我知道的最好方法是:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
有没有更好的办法?
#1楼
最简单的方法是:
vector<int> ints = {10, 20, 30};
#2楼
“我如何创建一个STL向量并像上面那样对其进行初始化?以最小的打字工作量,最好的方法是什么?”
在初始化内置数组时初始化向量的最简单方法是使用C ++ 11中引入的初始化列表。
// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};
// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);
在执行分配(标记语句)后,ivec的大小为3个元素。
#3楼
相关的,如果你想让一个向量完全准备好进入快速语句(例如,立即传递给另一个函数),你可以使用以下代码:
#define VECTOR(first,...) \
([](){ \
static const decltype(first) arr[] = { first,__VA_ARGS__ }; \
std::vector<decltype(first)> ret(arr, arr + sizeof(arr) / sizeof(*arr)); \
return ret;})()
示例功能
template<typename T>
void test(std::vector<T>& values)
{
for(T value : values)
std::cout<<value<<std::endl;
}
示例使用
test(VECTOR(1.2f,2,3,4,5,6));
虽然要小心decltype,但要确保第一个值显然是你想要的。
#4楼
在C ++ 11中:
#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };
使用boost list_of:
#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);
使用提升分配:
#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;
常规STL:
#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );
具有通用宏的常规STL:
#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));
具有向量初始化宏的常规STL:
#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);
#5楼
typedef std::vector<int> arr;
arr a {10, 20, 30}; // This would be how you initialize while defining
编译使用:
clang++ -std=c++11 -stdlib=libc++ <filename.cpp>
来源:oschina
链接:https://my.oschina.net/stackoom/blog/3154548