Reputation: 293
I'm getting a very strange error and something I've never experienced before, I'm trying to initialize a vector at declaration like so:
vector <int> myVector (5,4,3,4);
It gives me an error saying that it cannot find a call matching that function, however, if I plug in only 2 numbers it doesn't give me an error.
Upon further investigation, even this piece of code throws that vector is not a member of std or that myVector is not a type when I try to call
myVector.push_back(4);
Now here is the code that gives me the vector is not a member of std, not matching function found, of that nature...
#include <vector>
using std::vector;
const std::vector<int> newvector;
std::newvector.push_back(5);
int main()
{
}
Error given: newvector in namespace std does not name a type
Upvotes: 3
Views: 28384
Reputation: 145279
Regarding the final code example,
you can't have this statement outside a function body:
std::newvector.push_back(5);
Place it in main
's function body, and remove the std::
prefix.
Also note that for this vector modification to be possible, the vector can't be const
.
Initialization with round parentheses provides arguments to a constructor for the class. There must be a corresponding constructor. And there is no std::vector
constructor that corresponds to the four arguments in
vector <int> myVector (5,4,3,4);
Instead do
vector <int> myVector = {5,4,3,4};
If your compiler supports this C++11 syntax, that is.
If not, then the C++03 way would be
static int const data[] = {5,4,3,4};
static int const n_items = sizeof(data)/sizeof(data[0]);
vector <int> myVector( data, data + n_items );
Upvotes: 1
Reputation: 23644
std::newvector.push_back(5);
since newvector
is a variable, it is not in namespace std
.
For this case:
vector <int> myVector (5,4,3,4);
If you only use two values (5,4)
in this case, it will create a vector with size 5 and each of the elements initialized to 4 (one form of vector construction). If you need to initialize a vector with a list of values, you may try uniform initialization since C++11 as follows:
std::vector <int> myVector{5,4,3,4};
Some example of uniform initialization
can be found here: uniform initialization and other C++11 features
Upvotes: 3
Reputation: 29724
There are two issues with this code.
using std::vector;
brings a vector
from namespace std
but you have to use this as follows:
std::vector<int> newvector;
newvector.push_back(5);
You can notice that const dissapeared. This is because you want to change vector at last, so it cannot be const
, it would be compile error to call a push_back
on it otherwise.
Finally, this should be:
#include <vector>
using std::vector;
int main() {
std::vector<int> newvector;
newvector.push_back(5);
std::vector<int> newvector;
return 0;
}
Upvotes: 3
Reputation: 8805
The second error, you cannot initialize a vector
with its elements in the constructor, you must use its initializer list (C++11 only)
vector <int> myVector = {5,4,3,4};
Upvotes: 1