C++ 将元素替换为向量的特定位置

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6726805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 20:35:19  来源:igfitidea点击:

Replace an element into a specific position of a vector

c++visual-c++vectorstlinsert

提问by daiyue

I want to replace an element into a specific position of a vector, can I just use an assignment:

我想将一个元素替换到一个向量的特定位置,我可以只使用一个赋值:

// vec1 and 2 have the same length & filled in somehow
vec1;
vec2;

vec1[i] = vec2[i] // insert vec2[i] at position i of vec1

or I have to use insert():

或者我必须使用插入():

vector<sometype>::iterator iterator = vec1.begin();

vec1.insert(iterator+(i+1), vec2[i]);

回答by Armen Tsirunyan

vec1[i] = vec2[i]

will set the value of vec1[i]to the value of vec2[i]. Nothing is inserted. Your second approach is almost correct. Instead of +i+1you need just +i

将 的值设置vec1[i]为 的值vec2[i]。没有插入任何内容。你的第二种方法几乎是正确的。而不是+i+1你只需要+i

v1.insert(v1.begin()+i, v2[i])

回答by Pantelis Sopasakis

You can do that using at. You can try out the following simple example:

您可以使用at做到这一点。您可以尝试以下简单示例:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method atreturns an allocator_type::reference, which is that case is a int&. Using atis equivalent to assigning values like vec[i]=....

请注意,该方法at返回 an allocator_type::reference,即情况为 a int&。使用at等效于分配像vec[i]=....



There is a difference between atand insertas it can be understood with the following example:

atinsert之间有区别,可以通过以下示例来理解:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vecwe will get:

如果我们现在打印出来,vec我们将得到:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

相反,如果我们做了vec.at(2) = 10,或者vec[2]=10,我们会得到

1 2 10 4 5 0 0 0

回答by virlan2004

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/eg.:

在此处查看示例:http: //www.cplusplus.com/reference/stl/vector/insert/例如:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

您的第一种方法是将 vec1[i] 中的值替换为 vec2[i] 中的值