c++

c++ push_back函数能添加什么类型

小樊
82
2024-09-16 15:59:18
栏目: 编程语言

push_back() 是 C++ 中 std::vector 容器的一个成员函数,用于在向量的末尾添加一个元素。你可以将任何与向量元素类型相兼容的值或对象添加到向量中。

例如,如果你有一个 std::vector<int>,你可以使用 push_back() 添加整数:

#include<iostream>
#include<vector>

int main() {
    std::vector<int> numbers;
    numbers.push_back(1);
    numbers.push_back(2);
    numbers.push_back(3);

    for (int number : numbers) {
        std::cout<< number << " ";
    }

    return 0;
}

输出结果为:

1 2 3

同样,如果你有一个 std::vector<std::string>,你可以使用 push_back() 添加字符串:

#include<iostream>
#include<vector>
#include<string>

int main() {
    std::vector<std::string> words;
    words.push_back("hello");
    words.push_back("world");

    for (const std::string& word : words) {
        std::cout<< word << " ";
    }

    return 0;
}

输出结果为:

hello world

总之,push_back() 函数可以添加与向量元素类型相兼容的任何类型的值或对象。

0
看了该问题的人还看了