Форум » C/C++ для начинающих (C/C++ for beginners) » replace first value and last value in a vector » Ответить

replace first value and last value in a vector

ramees: 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

Сыроежка: You can use member functions front() and back() or the subscript operator. For example [pre2] #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; } [/pre2] The output is [pre2] 1 5 2 4 5 47 5 5 2 4 5 5 [/pre2] If you mean to exchange the first and the last elements of a vector then you can write simply [pre2] std::swap( v.front(), v.back() ); [/pre2]



полная версия страницы