加到一对向量上
Adding to a vector of pair
本文关键字:向量 更新时间:2023-10-16
我有pair
的vector
,类似于:
vector<pair<string,double>> revenue;
我想从这样的地图中添加一个字符串和一个替身:
revenue[i].first = "string";
revenue[i].second = map[i].second;
但由于收入没有初始化,它会出现一个越界错误。所以我试着这样使用vector::push_back
:
revenue.push_back("string",map[i].second);
但这不能包含两个论点。那么,我如何添加到pair
的vector
?
使用std::make_pair
:
revenue.push_back(std::make_pair("string",map[i].second));
IMHO,一个非常好的解决方案是使用c++11 template_back函数:
revenue.emplace_back("string", map[i].second);
它只是在适当的位置创建了一个新元素。
revenue.pushback("string",map[i].second);
但这不能包含两个论点。那么我怎样才能把它加到这个向量对上呢?
你走在正确的道路上,但要想一想;你的向量是什么?它当然不会在一个位置上包含字符串和int,而是包含Pair
。所以…
revenue.push_back( std::make_pair( "string", map[i].second ) );
或者您可以使用初始化列表:
revenue.push_back({"string", map[i].second});
阅读以下文档:
http://cplusplus.com/reference/std/utility/make_pair/
或
http://en.cppreference.com/w/cpp/utility/pair/make_pair
我认为这会有所帮助。这些网站是C++的好资源,尽管后者似乎是目前的首选参考。
revenue.push_back(pair<string,double> ("String",map[i].second));
这会奏效的。
您可以使用std::make_pair
revenue.push_back(std::make_pair("string",map[i].second));
尝试使用另一个临时对:
pair<string,double> temp;
vector<pair<string,double>> revenue;
// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);
使用emplace_back
函数比任何其他方法都要好,因为它创建了一个对象来代替类型为T
的vector<T>
,而push_back
需要您提供实际值。
vector<pair<string,double>> revenue;
// make_pair function constructs a pair objects which is expected by push_back
revenue.push_back(make_pair("cash", 12.32));
// emplace_back passes the arguments to the constructor
// function and gets the constructed object to the referenced space
revenue.emplace_back("cash", 12.32);
正如许多人建议的那样,您可以使用std::make_pair
。
但我想指出另一种同样的方法:
revenue.push_back({"string",map[i].second});
push_back((只接受一个参数,所以可以使用"{}"来实现这一点!
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么