C++ c++;向量<;字符串>;错误C2664
我对字符串数组有一些问题,我得到了使用向量而不是数组的建议。但这是可行的:C++ c++;向量<;字符串>;错误C2664,c++,string,vector,C++,String,Vector,我对字符串数组有一些问题,我得到了使用向量而不是数组的建议。但这是可行的: #include "stdafx.h" #include <string> #include <iostream> #include <vector> using namespace std; vector<int> a (1,2); void test(vector<int> a) { cout << a.size(); } int
#include "stdafx.h"
#include <string>
#include <iostream>
#include <vector>
using namespace std;
vector<int> a (1,2);
void test(vector<int> a)
{
cout << a.size();
}
int _tmain(int argc, _TCHAR* argv[])
{
test(a);
return 0;
}
#包括“stdafx.h”
#包括
#包括
#包括
使用名称空间std;
载体a(1,2);
无效测试(向量a)
{
cout第一个是调用构造函数(N,X)
,该构造函数创建N个元素,每个元素的值为X,因此最终得到一个2
第二个构造函数不匹配,因为没有一个构造函数使用两个const char*
或类似的构造函数
使用卷曲代替,因为有一个匹配的初始值设定项列表(至少在C++11中):
std::vector v{1,2};//包含1和2
std::vector v2{“hi”,“bye”};//包含“hi”和“bye”
在C++03中,您可以改为执行以下操作:
int vecInit[] = {1, 2, 3, 4};
std::vector<int> vec(vecInit, vecInit + sizeof vecInit / sizeof vecInit[0]);
intvecinit[]={1,2,3,4};
std::vector vec(vecint,vecint+sizeof vecint/sizeof vecint[0]);
最后,您将把数组中的项复制到向量中进行初始化,因为您使用的构造函数包含两个迭代器,其中指针是随机访问的。向量的构造函数不包含项列表,它只包含一个项和一个计数。std::vector
有多个构造函数其中一个参数期望元素数作为第一个参数,元素值作为第二个参数
在向量a(1,2)
的情况下,使用值为2的1个元素初始化向量a
对于向量a(“一”、“二”);
编译器无法将第一个参数转换为int(或其他构造函数的第一个参数所需的任何其他类型)
作为解决方法,您可以尝试以下方法:
std::string ch[] = {"one", "two"};
std::vector<std::string> a (ch, ch + _countof(ch));
std::string ch[]={“一”、“二”};
std::向量a(ch,ch+_countof(ch));
这将用两个字符串填充
a
:“一”和“二”
向量构造函数的第一个参数是元素的数量,第二个是这些元素的值
vectora(1,2)
表示值为2的1个元素,但没有向量匹配的构造函数vectora(“一”、“二”)
当第一次打印大小为1时,有些东西应该看起来有点可疑。只是为了将来,以防您没有意识到。如果您设计的函数适用于大型对象(如容器),则按值传递它们不是一个好主意。现在您正在制作一份完整的a
副本,以调用大小。无效测试(const vector&a)
将是更好的选择。
int vecInit[] = {1, 2, 3, 4};
std::vector<int> vec(vecInit, vecInit + sizeof vecInit / sizeof vecInit[0]);
std::string ch[] = {"one", "two"};
std::vector<std::string> a (ch, ch + _countof(ch));