When I assign int to vector I get an error says "conversion from 'int' to non-scalar type 'std::vector<int, std::allocator<int> >' requested
", what should I do?
I have vector varr(4, -1); what is the right way to 开发者_开发百科do "varr[2] = 3"?
They're two different types. If you want to add an int
to a vector<int>
do something like:
std::vector<int> vec;
vec.push_back(10);
Update: To set an element within the vector:
std::vector<int> vec(16, 0); // Create a 16 element vector containing all 0's
vec[4] = 10; // Sets the 5th element (0 based arrays) to 10
There appears to be a thorough codeguru tutorial which might be of interest.
A vector is a collection of ints. You can not assign an int to the collection, you add it to the collection using the push_back() function:
std::vector<int> manyInts;
int oneInt = 42;
manyInts.push_back(oneInt);
If you want to add the int
to to a vector<int>
you should use push_back
:
vector<int> v;
int i = 5;
v.push_back(i);
int sum = 468;
vector<int> v;
while(sum!=0){
v.push_back(sum%10);
sum /= 10;
}
reverse(v.begin(), v.end());
精彩评论