Wha*_*rld 1 c++ containers iterator
我有一个字符串向量和一个人向量。
vector<std::string> names
vector<Person> persons
Run Code Online (Sandbox Code Playgroud)
每个Person对象都有一个名称字段。现在我想从人中填充名字向量。除了使用for循环外,还有其他方法吗?
当然!标准算法是您的朋友;在这种情况下,它是std::transform:
// You'll need:
// <vector>
// <algorithm>
// <iterator>
const std::vector<Person> people = getPeople();
std::vector<std::string> names;
names.reserve(people.size());
std::transform(
std::begin(people),
std::end(people),
std::back_inserter(names),
[](const Person& person) { return person.name; }
);
Run Code Online (Sandbox Code Playgroud)
这最终将在for内部使用一个循环,对您而言是隐藏的。
std::vector但是,没有构造函数可以一口气做到这一点,对不起。您总是可以编写一个vector<string> GetNames(const vector<People>&)实用程序函数将其包装起来,然后就auto names = GetNames(people)在您的调用站点上。
取而代之的是捷径加一个转换运算符Person。这将起作用,并允许您直接names从Persons 范围进行初始化。
但是,就我个人而言,我发现隐式转换是绝对的威胁,这种特殊的隐式转换似乎对该类没有逻辑意义(除其他外,它的范围越来越窄,因为它丢弃了人的所有非命名部分)。
这种捷径感觉就像是一次明智的,廉价的胜利……然后,在三年的时间里,您会意识到,这一直是设计中大量技术债务的开始,您再也无法摆脱困境。我不建议这样做。
另外,说实话,for循环也很好。这是较少的代码。更多的人会知道它的作用。