c – 在运行时设置矢量类型
发布时间:2020-12-16 10:52:00 所属栏目:百科 来源:网络整理
导读:我有一个程序,需要在程序执行时设置向量的类型(根据配置文件中的值). 我试过这个: int a = 1if(a == 1) vectorint test(6);else vectorunsigned int test(6);test.push_back(3); 但这给了我: Error 1 error C2065: 'test' : undeclared identifier 我不完
我有一个程序,需要在程序执行时设置向量的类型(根据配置文件中的值).
我试过这个: int a = 1 if(a == 1) vector<int> test(6); else vector<unsigned int> test(6); test.push_back(3); 但这给了我: Error 1 error C2065: 'test' : undeclared identifier 我不完全确定原因,但我认为这是因为矢量实际上并不是在编译时决定的,因此编译器在编译其余代码时无法使用它. 有没有办法在运行时决定向量的类型,类似于我上面尝试的? 解决方法
它不起作用的原因是你分别在if-和else-block中声明了向量,因此一旦该块结束它们就会超出范围.
不,必须在编译时知道变量的类型.您唯一的选择是将test.push_back(3)行以及任何访问test的以下代码放入if-和else-block,或者避免代码复制到第二个模板化函数中.这看起来像这样: template <class T> do_something_with_test(vector<T>& test) { test.push_back(3); // work with test } void foo() { int a = 1 if(a == 1) { vector<int> test(6); do_something_with_test(test); } else { vector<unsigned int> test(6); do_something_with_test(test); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |