根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
Fill vector with alphabets depending on user input and put Start and End on the extremities
我正在尝试使向量看起来像这样: alphabet= {开始,A,B,C,D,E,F,G,H,I,J,K,等等,结束}
字母表不是从 A 到 Z,而是用户输入值。 因此,如果用户输入 5,我希望向量为: {开始,A,B,C,D,E,end}
我尝试使用 iota,但我不知道如何在矢量的末端推动"开始"和"结束">
vector<string> alphabet;
iota(alphabet.start(), alphabet.end(), 'A');
如何推动start
和end
值?
对于字母表的前 5 个字母
#include <iostream>
#include <vector>
#include <string>
#include <numeric>
int main() {
// vector needs to be allocated, +2 is for start and end
std::vector<std::string> alphabet(5+2);
// front() gives you reference to first item
alphabet.front() = "start";
// end() gives you reference to last item
alphabet.back() = "end";
// you can use iota, but skipping the first and last item in vector
std::iota(std::next(alphabet.begin()), std::prev(alphabet.end()), 'A');
for (const auto& S : alphabet)
std::cout<<S<< ", ";
}
此代码块的输出为:start, A, B, C, D, E, end,
我认为你想要的是这样的东西:
int numberOfLetters;
std::cin >> numberOfLetters;
std::vector<char> characters(numberOfLetters);
for(int i = 0; i < numberOfLetters; i++)
{
characters[i] = 65 + i;
}
这将起作用,因为字符使用 ASCII 编码,而"A"的 ASCII 值为 97,并且从那里开始增加,因此 65 + 0 = 'A',65 + 1 = 'B',依此类推。(当然包括向量来访问std::vector,或者使用C数组,如:char* characters = malloc(numberOfLetters);
这里需要注意:你不需要使用数字65,你可以这样写"A":
characters[i] = 'A' + i;
因为字符可以添加,因为它们可以表示为数字。(丘里尔建议)
相关文章:
- 当回溯以零开始时,如何调试崩溃
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 如何从头开始创建 avi 文件?
- 为什么 -mmacosx-version-min=10.10 不阻止使用标记为从 10.11 开始的函数?
- 自一周开始以来的秒数?
- 一旦双簧管录制开始,主 UI 线程就会被阻止
- GStreamer在开始任何播放之前进行搜索
- 使 std::fstream 写入文件末尾,但从头开始读取
- 如何以毫秒为单位获取开始时间和 now() 之间的毫秒差异(以 C++为单位?
- 哪个C++规范开始支持 std::vector
- 如何继续读取不同功能中的文件,而不是从头开始再次读取文件?
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 如何在调试中通过传递引用开始
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 从特定键开始遍历地图
- 列表的有效性在插入后开始迭代器
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 试图修复一个错误,该错误不会让我开始编程其余部分
- 甚至在开始执行之前出现分段错误
- 为什么 Glib::VariantBase::store 方法破坏了给定缓冲区的开始