c – 在运行时设置矢量类型

c – 在运行时设置矢量类型,第1张

概述我有一个程序,需要在程序执行时设置向量的类型(根据配置文件中的值). 我试过这个: int a = 1if(a == 1) vector<int> test(6);else vector<unsigned int> test(6);test.push_back(3); 但这给了我: Error 1 error C2065: 'test' : undeclared identi 我有一个程序,需要在程序执行时设置向量的类型(根据配置文件中的值).

我试过这个:

int a = 1if(a == 1)  vector<int> test(6);else  vector<unsigned int> test(6);test.push_back(3);

但这给了我:

Error   1   error C2065: 'test' : undeclared IDentifIEr

我不完全确定原因,但我认为这是因为矢量实际上并不是在编译时决定的,因此编译器在编译其余代码时无法使用它.

有没有办法在运行时决定向量的类型,类似于我上面尝试的?
我试图在if之外创建一个版本然后删除它并在IF中重新编写新版本.然而这感觉不对,无论如何我无法让它工作.
谢谢.

解决方法 它不起作用的原因是你分别在if-和else-block中声明了向量,因此一旦该块结束它们就会超出范围.

Is there a way to decIDe the type of a vector at runtime similar to what I have attempted above?

不,必须在编译时知道变量的类型.您唯一的选择是将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);    }}
总结

以上是内存溢出为你收集整理的c – 在运行时设置矢量类型全部内容,希望文章能够帮你解决c – 在运行时设置矢量类型所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1223448.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存