开发者

assigning vector

how I 开发者_JAVA百科can assign v[i] to an series of integers ( type of v is vector ) without initially filling inside


Do you mean initializing std::vector to a series of integers?

int i[] = {1, 2, 3, 4, 5};
std::vector<int> myVector(i, i+ (sizeof(i)/sizeof(int)));

If you meant to create a vector of some elements so you can perform the assignment using their index values. Here, the following statement declares and initializes a vector with its elements being default initialized to 0.

std::vector<int> myVector(5); // constructs a vector of size five integers.

for (int x = 0; x < 5; x++)
    myVector[x] = i[x];     // assign values using subscript [..] 

But I think the even better way to go would be as @CashCow mentioned in his answer.

Also, note that you can also pre-allocate memory to add elements into the vector with avoiding any repeated memory allocations.

For example:

std::vector<int> myVector; // empty vector for integers
myVector.reserve(5); // pre-allocates memory for five integers

for (int i = 0; i < 5; i++) // now, you can add your elements
    myVector.push_back(i);

It is usually a good idea to pre-allocate memory if you know the size of elements i.e in case of large number of elements when the performance is an important factor.


If you have anything that has the traits of an iterator you can use vector's assign method:

std::vector<int> v;
v.assign( iterStart, iterEnd );
  • iterStart should be such that *iterStart is the first value you want to add.
  • iterEnd should be one past the end, it is a terminating condition
  • ++iter would move you to the next iterator in the input series.

I don't know what you mean by assign v[i] though. You cannot assign an element to a series. If you want to write the series at a location into an existing vector you can use insert instead of assign.


common way of adding items is calling std::vector<>push_back() method.

std::vector<int> myVector;
myVector.push_back(5);
myVector.push_back(10);
myVector.push_back(3);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜