You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中Vector初始化:如何用英文字母初始化大小为26的vector?

Initializing a C++ std::vector (with a focus on 26 English letters)

Hey there! Let's walk through common ways to initialize a std::vector in C++, with a deep dive into the specific case of creating a 26-element vector filled with the English alphabet (lowercase or uppercase).

Basic std::vector Initialization Methods

First, a quick recap of general initialization approaches to set the stage:

  • Default initialization: Creates an empty vector: std::vector<char> empty_vec;
  • Fixed size with default value: Creates a vector of N elements, all set to a default: std::vector<char> vec(26, ' '); (26 spaces)
  • Copy initialization: Creates a vector as a copy of another: std::vector<char> copied_vec = existing_vec;

Target: 26-Element Vector with English Letters

Now let's get to the specific use case—here are 3 practical methods to populate a vector with all 26 letters:

1. Simple Loop Assignment (Most Intuitive)

This is the easiest approach for beginners, leveraging the fact that ASCII characters for letters are contiguous:

#include <vector>

int main() {
    // Initialize a vector with 26 empty slots first
    std::vector<char> lowercase_letters(26);
    
    // Fill with 'a' to 'z'
    for (int i = 0; i < 26; ++i) {
        lowercase_letters[i] = 'a' + i;
    }

    // For uppercase letters, just swap 'a' with 'A'
    std::vector<char> uppercase_letters(26);
    for (int i = 0; i < 26; ++i) {
        uppercase_letters[i] = 'A' + i;
    }
}

Pro tip: This works because in ASCII (and most modern character encodings), 'a' through 'z' are sequential integers—adding i increments the character value correctly.

2. Initializer List (Explicit but Verbose)

If you prefer writing out all elements explicitly (great for clarity, though a bit tedious for 26 letters):

#include <vector>

int main() {
    std::vector<char> lowercase_letters = {
        'a','b','c','d','e','f','g','h','i','j',
        'k','l','m','n','o','p','q','r','s','t',
        'u','v','w','x','y','z'
    };

    // Uppercase version follows the same pattern
    std::vector<char> uppercase_letters = {
        'A','B','C','D','E','F','G','H','I','J',
        'K','L','M','N','O','P','Q','R','S','T',
        'U','V','W','X','Y','Z'
    };
}

This method ensures the vector is initialized exactly as you specify, with no runtime loops.

3. STL std::generate Algorithm (Clean, Idiomatic C++)

For a more concise, STL-style approach, use std::generate (requires including <algorithm>):

#include <vector>
#include <algorithm>

int main() {
    std::vector<char> lowercase_letters(26);
    char current_char = 'a';
    
    // Use a lambda to generate each element
    std::generate(lowercase_letters.begin(), lowercase_letters.end(), 
                  [&current_char]() { return current_char++; });

    // Uppercase variant
    std::vector<char> uppercase_letters(26);
    char current_upper = 'A';
    std::generate(uppercase_letters.begin(), uppercase_letters.end(),
                  [&current_upper]() { return current_upper++; });
}

The lambda captures current_char by reference, incrementing it each time it's called to produce the next letter. This is a great choice if you want to keep your code concise and leverage STL tools.

Bonus: Convert Between Cases

If you need to generate uppercase from lowercase (or vice versa), use std::toupper/std::tolower (include <cctype>):

#include <vector>
#include <algorithm>
#include <cctype>

int main() {
    std::vector<char> uppercase_letters(26);
    char current_char = 'a';
    std::generate(uppercase_letters.begin(), uppercase_letters.end(),
                  [&current_char]() { return static_cast<char>(std::toupper(current_char++)); });
}

Note: std::toupper returns an int, so we cast it back to char to avoid type issues.

Hope these methods give you flexibility to choose what fits your code style best!

内容的提问来源于stack exchange,提问作者shirazy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 09:02:41