有没有办法在 C++ 中索引值组

is there a way to index groups of values in c++

我想知道是否有办法排除索引或获取一组索引。例如,假设我有一个字符串。我想要最后 3 个字符并将它们放入一个字符串变量中。有没有办法在没有 for 循环或 user-defined/external 函数的情况下做到这一点?

string coolstring = "coolstr";
string CoolStringWithoutTheCool = coolstring[4-6] // trying to grab the last 3 values ("str")

是的,你可以使用 substr

std::string x = coolstring.substr(4, 2);

C++中,切片的概念通常由迭代器来满足。

迭代器就像指向元素的指针,beginend 两个迭代器定义了一个范围。

所以,在你的情况下,你会想要

string CoolStringWithoutTheCool = std::string(coolstring.begin() + 4, coolstring.begin() + 7);

字符串有一种特殊的方法,称为substr,它的作用相同

string CoolStringWithoutTheCool = coolstring.substr(4, 3); // You want the length to be 3