c++ - 具有两种类型的模板 vector

标签 c++ templates vector

我看了相关的帖子,还是想不通。 在我的 .h 文件中,我定义了一个模板类:

template <typename P, typename V>
class Item {
 public:
    P priority;
    V value;
    Item(P priority, V value): priority(priority), value(value){}
};

在我的主要功能中,我试图制作一个具有特定类型的项目 vector 。

Item<int, string> Item1(18, "string 1");
Item<int, string> Item2(16, "string 2");
Item<int, string> Item3(12, "string 3");
Item<int, string> Item[3] = {Item1, Item2, Item3}
vector<Item<int, string> > Items(Item, Item + 3);

但我不断收到编译错误:

expected '(' for function-style cast or type construction
vector<Item<int, string> > Items(Item, Item + 9);
            ~~~^

最佳答案

这是工作代码

#include<iostream>
#include<vector>
using namespace std;
template <typename P, typename V>
class Item
{
public:
    P priority;
    V value;
    Item(P priority, V value): priority(priority), value(value) {}
};
int main()
{
    Item<int, string> Item1(18, "string 1");
    Item<int, string> Item2(16, "string 2");
    Item<int, string> Item3(12, "string 3");
    Item<int, string> ItemL[3] = {Item1, Item2, Item3}; 
    vector<Item<int, string> > Items(ItemL, ItemL+3);
}

你有几个问题:

  1. Item<int, string> Item[3] = {Item1, Item2, Item3} 后缺少分号行
  2. Item<int, string> Item[3] line 你的类(class)名称 Item和名为 Item 的项目数组模糊的。所以将它重命名为其他名称,我将其重命名为 ItemL

关于c++ - 具有两种类型的模板 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33250120/

相关文章:

c++ - 一组类型的模板特化

c++ - 跨文件的代码组织,这些文件必须处理模板功能和内联

javascript - emberjs - 在更大的模板中有条件地渲染模板

C++ 避免全局变量和单例

c++ - 并发 std::vector 写入的效率

c++ - 如果给定一个 15 位数字,找到下一个回文的最佳方法是什么?

c++ - c++ armadillo 如何在for循环中加速调用一个巨大的 vector

c++ - 如果为空,则从 QListWidget 中删除可编辑项

C++模板类编译错误: expected init-declarator before '<' token

c++ - 查找 vector<string> 中的所有元素是否都在字符串中