简体   繁体   English

C++ 用于向量中的结构访问索引或使用引用代替值

[英]C++ for structure in vectors access index or use reference instead value

I assume that if I ve got, for example:我假设如果我有,例如:

vector<string> myVector;
myVector.push_back("Camel");
myVector.push_back("is");
myVector.push_back("a");
myVector.push_back("noble");
myVector.push_back("animal");

And I do:我这样做:

for (string val : myVector){
    val = "empty";
}

It does not replace value in vector since it has copied content to a new string.它不会替换 vector 中的值,因为它已将内容复制到新字符串。

I assume I can do我想我能做到

for (int i=0; i<myVector.size(); i++) {
    myVector[i] = "empty";
}

It will perform the behaviour.它将执行该行为。

But well.但是很好。 My question is:我的问题是:

There exist any other structure similar to first case where I can say "Pick the reference of the value in the vector instead of you copy value to a new variable" then I can directly affect to vector values instead and having the for (class value : vector) typing model?存在与第一种情况类似的任何其他结构,我可以说“选择向量中值的引用,而不是将值复制到新变量”,然后我可以直接影响向量值,并使用for (class value : vector)打字模型?

Or Best practices for the example without use any of the cases I mentioned?或者示例的最佳实践不使用我提到的任何情况? Iterator?迭代器?

Declare your range based for loop to initialize a reference to each item:声明基于 for 循环的范围以初始化对每个项目的引用:

for (string& val : myVector){
    val = "empty";
}

Now the vector's items are modified in-place.现在矢量的项目就地修改了。 The type of the "item" can be anything for which... “项目”的类型可以是任何...

<item-type> declarator = *itr;

... is valid when itr is an iterator of the container. ... 当itr是容器的迭代器时有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM