Keeping the first N elements of a std::vector<> and removing the rest

后端 未结 1 1762
情话喂你
情话喂你 2020-12-29 02:53

I have a std::vector variable in my C++ application. The size of the vector is determined at runtime, but is typically about 1000<

相关标签:
1条回答
  • 2020-12-29 03:23

    Yes, you can use std::vector::resize, which just truncates if the length of the vector is greater than n.

    See here: http://www.cplusplus.com/reference/vector/vector/resize/

    std::vector<int> myvector;
    
    for (int i=1;i<1000;i++) myvector.push_back(i);
    
    myvector.resize(50);
    // myvector will contain values 1..50
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题