c++用数组初始化向量

In this article, we’ll take a look at some of the ways to initialize a vector in C++. There are a bunch of ways to do this, so we’ll go through each approach.

在本文中,我们将介绍一些在C ++中初始化向量的方法。 有很多方法可以做到这一点,因此我们将介绍每种方法。

Let’s get started!

让我们开始吧!



方法1 :(推荐):使用初始化列表(C ++ 11及更高版本) (Method 1: (Recommended): Use an Initializer List (C++11 and above))

If your compiler supports the C++ version above C++11, you can simply initialize the vector using the {} notation.

如果您的编译器支持C ++ 11以上的C ++版本,则可以简单地使用{}表示法初始化向量 。

Since std::vector is a class, to initialize an object of this class using the above fashion, this refers to an Initializer List in C++.

由于std :: vector是一个类,因此要使用上述方式初始化该类的对象,因此它指的是C ++中的Initializer List 。

Here is an example using the initializer list declaration:

这是使用初始化列表声明的示例:


std::vector<int> vec = { 1, 2, 3, 4, 5 };

Since initializer lists were introduced only in C++11, you need a minimum compiler version supporting at least C++11 to use this method.

由于初始化程序列表仅在C ++ 11中引入,因此您需要至少支持C ++ 11的最低编译器版本才能使用此方法。

Here is an example program to demonstrate this type of initialization:

这是一个示例程序来演示这种类型的初始化:


#include <iostream>
#include <vector>int main() {// Initialize a vector<int> using Initializer Listsstd::vector<int> vec = { 1, 2, 3, 4, 5 };// Use a range based for loop to print elements of the vectorfor (const auto &i: vec) {// Using access by reference to avoid copying// Using const since we're not modifying elements of the vectorstd::cout << i << std::endl;}return 0;
}

Here, we use a range-based for-loop to print the vector elements.

在这里,我们使用基于范围的for循环来打印矢量元素。

Output

输出量


1
2
3
4
5

方法2:借助数组(C ++ 0x)在C ++中初始化Vector (Method 2: Initialize a Vector in C++ with the help of an array (C++0x))

If you’re using a C++0x (C++03, C++07, etc) based compiler, you can still achieve the initialization using arrays.

如果您使用的是基于C ++ 0x (C ++ 03,C ++ 07等)的编译器,则仍可以使用数组实现初始化。


int tmp[] = { 1, 2, 3, 4, 5 };
std::vector<int> vec( tmp, tmp + sizeof(tmp)/sizeof(tmp[0]) );

Test this on a C++0x based compiler, to verify that it works.

在基于C ++ 0x的编译器上进行测试,以验证其是否有效。


#include <iostream>
#include <vector>using namespace std;int main() {// Initialize a vector<int> using Arraysint tmp[] = { 1, 2, 3, 4, 5 };std::vector<int> vec(tmp, tmp + sizeof(tmp)/sizeof(tmp[0]));// Range based for loops not supported in older compilers!// Nor is auto!for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {std::cout << *it << std::endl;}return 0;
}

If you’re on Linux (g++ based compiler), compile and run using:

如果您使用的是Linux(基于g ++的编译器),请使用以下命令进行编译和运行:


gcc -o test.out test.cpp -std=c++0x
./test.out

Output

输出量


1
2
3
4
5

方法3:使用<boost>库(C ++ 11及更高版本) (Method 3: Using the <boost> library (C++11 and above))

We can also use the <boost> library to achieve this.

我们还可以使用<boost>库来实现此目的。

The <boost/assign> namespace has the list_of construct to initialize vectors.

<boost / assign>名称空间具有用于初始化向量的list_of构造。


#include <boost/assign/list_of.hpp>// Initialize a vector of {1, 2, 3, 4, 5}
std::vector<int> vec = boost::assign::list_of(1)(2)(3)(4)(5);

We can also use the overloaded + operator to declare a vector and add elements.

我们还可以使用重载的+运算符声明一个向量并添加元素。


// Courtesy: https://stackoverflow.com/a/2236233#include <boost/assign/list_of.hpp>// Declare a vector
std::vector<int> vec;// Add elements to it
vec += 1, 2, 3, 4, 5;

However, this type of operator overloading is not advisable, as it can be confusing for many readers, as a person reading this code may also think that the first element will add to 1, the second element adding to 2, etc.

但是,这种类型的运算符重载是不可取的 ,因为它可能会使许多读者感到困惑,因为阅读此代码的人可能还会认为第一个元素将加1,第二个元素加2,依此类推。



结论 (Conclusion)

In this article, we learned how we could initialize a vector in the C++ language in different ways.

在本文中,我们学习了如何以不同的方式用C ++语言初始化向量。



参考资料 (References)

  • StackOverflow Question on initializing vectors关于初始化向量的StackOverflow问题
  • JournalDev Article on Initializer ListsJournalDev关于初始化程序列表的文章


翻译自: https://www.journaldev.com/37575/initialize-a-vector-in-c-plus-plus

c++用数组初始化向量

c++用数组初始化向量_用C ++初始化向量相关推荐

  1. bn层初始化参数_神经网络参数初始化方式

    看了文章<Understanding the difficulty of training deep feedforward neural networks>,里面提出了两种参数初始化的方 ...

  2. 随机生成元素升序向量_推荐系统中用户向量的表示学习

    随着深度学习在推荐系统中的应用,embedding成为绕不开的话题.无论是召回还是排序阶段,均应用到embedding技术.目前已经有很多文章在讨论item的embedding如何生成,本文希望讨论u ...

  3. python定时重新初始化类_如何重新初始化类对象

    我正在制作一个典型的文本游戏程序,我被困在重启功能上.我想重新启动room实例,但是当我试图删除对象时,我得到AttributeError:room1.下面是一些伪代码:class Room: inv ...

  4. cnn 句向量_快速理解句向量模型,深度好文,一定要看

    微信文章排版好看一些,在这里:https://mp.weixin.qq.com/s?__biz=MzIyNTY1MDUwNQ==&mid=2247483961&idx=1&sn ...

  5. python无法初始化设备_【无法初始化这个硬件设备驱动程序】无法初始化这个硬件的设备驱动_无法初始化d3d...

    2017-08-25 16:30:37 在安装驱动的过程中也会出现很多问题,有的win7用户在安装驱动失败后,在设备管理器中有个硬件前有感叹号,打开属性一看,显示"Windows无法初始化这 ...

  6. c++ stl队列初始化_声明,初始化和访问向量| C ++ STL

    c++ stl队列初始化 Here, we have to declare, initialize and access a vector in C++ STL. 在这里,我们必须声明,初始化和访问C ...

  7. java中数组的含义_数组

    数组(Array)是有序的元素序列.[1] 若将有限个类型相同的变量的集合命名,那么这个名称为数组名.组成数组的各个变量称为数组的分量,也称为数组的元素,有时也称为下标变量.用于区分数组的各个元素的数 ...

  8. winform point数组带数值_带你学够浪:Go语言基础系列 - 8分钟学复合类型

    对于一般的语言使用者来说 ,20% 的语言特性就能够满足 80% 的使用需求,剩下在使用中掌握.基于这一理论,Go 基础系列的文章不会刻意追求面面俱到,但该有知识点都会覆盖,目的是带你快跑赶上 Gol ...

  9. java 数组的方法_数组常用方法

    [TOC] # 定义 ~~~ //初始化一个长度为8的定长数组,其所有元素均为0 val arr1 = new Array[Int](8) //直接打印定长数组,内容为数组的hashcode值 pri ...

最新文章

  1. 语义分割--Large Kernel Matters--Improve Semantic Segmentation by Global Convolutional Network
  2. SVN地址正确,能在网页打开,但是检出失败解决方法
  3. 手机软件:杀手游戏的法官助手,(人多的时候法官没有辅助,是很难记住各个角色的)...
  4. Linux进程实践(1) --Linux进程编程概述
  5. makefile的两个变量(自动变量和普通变量)
  6. Python 第三方模块之 psutil - 获取系统运行的进程和系统利用率信息
  7. 菜鸟驿站:今年双11期间全国站点将普遍延长营业时间
  8. 基于PCA的特征提取
  9. 反爬虫绕过初级——添加http header和gzip解压处理
  10. Android 分享到LINE
  11. 多人在线匿名聊天室/私人聊天室源码/支持同时创建多个聊天室
  12. 2020下半年教师资格证《幼儿综合素质》真题及答案
  13. 投资人为什么盯上了这些“小巨人”?
  14. 使用python将txt格式的数据转换为csv格式,读取csv数据前几行
  15. 字节跳动小程序对接环信IM遇到的问题
  16. C++ 数据结构学习 ---- 栈及其应用
  17. 第16集丨阳明心学量子力学
  18. 研一一整年都在搞深度学习,研二醒悟打算转开发
  19. yuyv_to_yv12
  20. matlab--图像颜色反转

热门文章

  1. mock SpringMVC 测试控制器方法
  2. 浅析foreach原理
  3. [原]批量生成AWR报告
  4. 【转】[Python Tip]如何在Windows下方便地进入命令行运行程序
  5. Csdn Blog 开发团队致广大网友的一封信
  6. [转载] Python3 open()函数
  7. [转载] Python-科赫雪花(科克曲线)
  8. verilog之状态机详细解释(二)
  9. 如何实现一个Servlet中的多个功能
  10. 为什么需要使用Git客户端?