std::vector.push_back() C++

std::vector.push_back() C++

我想使用 push_back 函数用字母初始化一个向量。这是正确的做法吗?

vector<char> v;
char letter = 'A';
for(int i=0; i<26; i++)
{
    v.push_back(letter+i);
}

有效。我只是想知道在将 i 添加到 int 之前是否应该使用类型转换字母?

或者有更高效的方法吗?

请注意,您的代码依赖于对字母进行连续编码的字符编码方案,例如ASCII.

如果该假设成立,您可以最初使用正确的大小创建向量,然后使用 std::iota 初始化所有元素:

std::vector<char> v(26);  // Create a vector of 26 (default-initialized) elements
std::iota(begin(v), end(v), 'A');  // Assign a letter to each element in the vector

如果您希望您的代码可移植到字母未连续编码的系统(如使用 EBCDIC 的系统),那么您最好明确地使用字母创建一个字符串:

std::string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";  // Thanks Nathan Oliver :)

如果你有一个包含所有字母的字符串,那么也许你甚至不需要向量。

看起来不错!

  • 我想也许 std::array() 也是一个选项,与 std::vector() 相比,用于类似任务:
#include <iostream>
#include <array>
#include <vector>
#include <chrono>

void function1() {
    std::vector<char> alphabets;

    for (unsigned int index = 0; index < 26; ++index) {
        alphabets.push_back(index + 'A');
        // std::cout << alphabets[index] << "\t";
    }

    // std::cout << "\n\n";
}

void function2() {
    std::vector<char> alphabets;

    for (unsigned int index = 0; index < 26; ++index) {
        alphabets.emplace_back(index + 'A');
        // std::cout << alphabets[index] << "\t";
    }

    // std::cout << "\n\n";
}

void function3() {
    std::array<char, 26> alphabets;

    for (unsigned int index = 0; index < 26; ++index) {
        alphabets[index] = index + 'A';
        // std::cout << alphabets[index] << "\t";
    }

    // std::cout << "\n\n";
}

int main() {

    const auto t1 = std::chrono::high_resolution_clock::now();

    for (std::size_t i = 0; i < 1000000; ++i) {
        function1();
    }

    const auto t2 = std::chrono::high_resolution_clock::now();
    const auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();

    std::cout << duration <<
              " is the rough runtime of std::vector function with push_back\t\t\n\n";



    const auto t3 = std::chrono::high_resolution_clock::now();

    for (std::size_t i = 0; i < 1000000; ++i) {
        function2();
    }

    const auto t4 = std::chrono::high_resolution_clock::now();
    const auto duration2 = std::chrono::duration_cast<std::chrono::microseconds>( t4 - t3 ).count();

    std::cout << duration2 <<
              " is the rough runtime of std::vector function with emplace_back\t\t\n\n";


    const auto t5 = std::chrono::high_resolution_clock::now();

    for (std::size_t i = 0; i < 1000000; ++i) {
        function3();
    }

    const auto t6 = std::chrono::high_resolution_clock::now();
    const auto duration3 = std::chrono::duration_cast<std::chrono::microseconds>( t6 - t5 ).count();

    std::cout << duration3 << " is the rough runtime of std::array function\t\t\n\n";

    return 0;
};