C++ - 令牌之前的预期主表达式'('并且缺少"("标记之前的模板参数

C++ - Expected primary expression before '(' token AND missing template arguments before ‘(’ token

本文关键字:参数 表达式 C++ 令牌      更新时间:2023-10-16

我定义

typedef std::map< int, std::set<int> > SparseMap;

然后我试着用这种方式插入一对:

pair<SparseMap::iterator,bool> result;
result = sparseBlue.insert(SparseMap::value_type(row, set(col)) ); //errors
   if(result.second)
         cout << "Inserted" << endl;
  • 和列是整数矩阵坐标
  • 稀疏蓝色声明为SparseMap sparseBlue;

为什么我在插入的行中出现这些错误?

我相信@T.C和@Lightness Races在轨道上使用std::set<int>的想法是正确的。唯一的问题是std::set<T>没有一个接受构造函数的构造函数,该构造函数接受t类型的单个项(在本例中为int)。

假设你真的需要一个集合作为地图中的值,那么你可能想要这样的东西:

std::set<int> tmpSet;
tmpSet.insert(col);
result = sparseBlue.insert(std::make_pair(row, tmpSet));

另一个解决方案是,您可以在添加项目之前插入到地图中:

#include <map>
#include <set>
using namespace std;
int main() 
{
    int row = 0;
    int col = 0;
    std::map<int, set<int>> sparseBlue;
    // insert empty item
    auto iter = sparseBlue.insert(std::make_pair(row, std::set<int>()));
    // did a new item get inserted?
    cout << "The item did " << (iter.second?"":"not") << " get insertedn";
    // add item to set 
    (*iter.first).  // the map iterator
           second.  // the set
           insert(col); // what we want to do 
}

std::map::insert的返回值返回一个std::pair,表示插入项的迭代器,以及truefalse,具体取决于是否插入了新项。

实例