您可以使用 vector.size() 函数来获取 vector 中元素的数量,并将其存储在一个变量中。以下是一个示例代码:

#include <iostream>
#include <vector>
#include <sstream>

using namespace std;

int main() {
    vector<int> v = {1, 2, 3, 4, 5};
    stringstream ss;
    ss << v.size();
    string str = ss.str();
    cout << "The number of elements in the vector is " << str << endl;
    return 0;
}

在上面的代码中,我们使用 stringstream 来将整数值转换为字符串,然后将其存储在变量 str 中,最后将其输出到控制台。您可以根据自己的需要来更改输出的格式。

C++ 获取vector元素数量并存储到变量

原文地址: https://www.cveoy.top/t/topic/owJ5 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录