[英]how to use emplace_back to insert a new element into a vector of vector?
I'm confused by the syntax of some C++ concepts.我对一些 C++ 概念的语法感到困惑。
Let's say I have a vector of vector:假设我有一个向量向量:
vector<vector<int>> data;
I can use push_back()
to insert a new element:我可以使用
push_back()
插入一个新元素:
data.push_back({1, 1});
In this way, I list initialized a new element, then a copy of this element is pushed to data
?这样,我列表初始化了一个新元素,然后将这个元素的副本推送到
data
?
I can also do it in this way:我也可以这样做:
vector<int> tmp{1, 1};
data.emplace_back(tmp);
But if I directly call emplace()
, like in this way:但是如果我直接调用
emplace()
,就像这样:
data.emplace_back(1, 1);
It does not give me the expected result.它没有给我预期的结果。
Did I misunderstand something here?我在这里误解了什么吗?
---update: sorry, what I mean is emplace_back
. ---更新:对不起,我的意思是
emplace_back
。 My question is how to initialize directly using emplace_back
instead of initializing a tmp vector first, vector<int> tmp{1, 1};
我的问题是如何直接使用
emplace_back
进行初始化,而不是先初始化一个 tmp 向量vector<int> tmp{1, 1};
. .
I can use push_back to insert a new element: data.push_back({1, 1});
我可以使用 push_back 插入一个新元素: data.push_back({1, 1}); In this way, I list initialized a new element, then a copy of this element is pushed to data?
这样,我在list中初始化了一个新元素,然后把这个元素的副本推送到数据中?
exactly.确切地。
data.emplace(1, 1);
data.emplace(1, 1);
vector<Type>::emplace_back
forwards its arguments to the constructor of Type
. vector<Type>::emplace_back
将其 arguments 转发给Type
的构造函数。 Now, std::vector<int>
has a constructor that takes two integer arguments.现在,
std::vector<int>
有一个构造函数,它接受两个 integer arguments。 The one specifying length (1) and fill element (1).一个指定长度 (1) 和填充元素 (1)。
You can, however, inform the compiler you actually mean list initialization!但是,您可以告知编译器您实际上是指列表初始化!
#include "fmt/format.h"
#include "fmt/ranges.h"
#include <initializer_list>
#include <vector>
int main() {
std::vector<std::vector<int>> a;
a.emplace_back(std::initializer_list<int>{1, 1});
a.emplace_back(std::initializer_list<int>{2, 2});
fmt::print("{}\n", fmt::join(a.begin(), a.end(), ";"));
}
yields the expected产生预期的
{1, 1};{2, 2}
There is an emplace function, but this takes an iterator ( see docs ).有一个 emplace function,但这需要一个迭代器(请参阅文档)。
emplace_back
will add a new element to the end of the vector. emplace_back
将在向量的末尾添加一个新元素。
emplace
emplaces the element at a specified a position indicated by an iterator. emplace
将元素放置在由迭代器指示的指定 position 处。 v.emplace_back(1)
and v.emplace(v.end(), 1)
are the same, because the indicated position is the end of v
. v.emplace_back(1)
和v.emplace(v.end(), 1)
相同,因为指示的 position 是v
的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.