Автор | Сообщение |
|
Отправлено: 23.06.14 18:06. Заголовок: replace first value and last value in a vector
how can i replace first element and last element in a vector i try to insert but its append value to it . my vector values -> {1,5,2,4,5,47} i need to replace value first value 1 , and last value 47, with other value how can i do that #include <iostream> #include <vector> using namespace std; const int x = 6; int main() { int a[x]={1,5,2,4,5,47}; vector<int> v(a,a+x); int c = v.size(); v.insert(v.begin(),5); for(int f = 0; f<v.size();f++){ cout<<v[f]<<endl; } return 0; }
|
|
|
Ответов - 1
[только новые]
|
|
|
Отправлено: 23.06.14 18:41. Заголовок: You can use member f..
You can use member functions front() and back() or the subscript operator. For example #include <iostream> #include <vector> int main() { std::vector<int> v = { 1, 5, 2, 4, 5, 47 }; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; v.front() = 5; v.back() = 5; // v[0] = 5; v[v.size() - 1] = 5; for ( int x : v ) std::cout << x << ' '; std::cout << std::endl; return 0; } The output is 1 5 2 4 5 47 5 5 2 4 5 5 If you mean to exchange the first and the last elements of a vector then you can write simply std::swap( v.front(), v.back() );
|
|
|