I had some problem with string arrays C++ array size different result I got the advice to use vectors instead of arrays. But this works:
#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;
}
But this wont:
vector<string> a ("one", "two");
void test(vector<string> a)
{
cout << a.size();
}
int _tmain(int argc, _TCHAR* argv[])
{
test(a);
return 0;
}
error C2664: ‘std::basic_string<_Elem,_Traits,_Ax>::basic_string(const std::basic_string<_Elem,_Traits,_Ax> &)’ : cannot convert parameter 1 from ‘const char’ to ‘const std::basic_string<_Elem,_Traits,_Ax> &’
I dont get whats going wrong.
The first one is calling a constructor
(N, X)that creates N elements, each with a value of X, so you end up with one 2.There is no match for the second constructor, as none take two
const char *or similar.Use curlies instead, as there is a match for an initializer list (at least in C++11):
In C++03, you can instead do this:
You’ll end up copying the items from the array into the vector to initialize it because you utilize the constructor that takes two iterators, of which pointers are random-access.