急求,如何实现Vector中两个元素值的交换!
大侠,在STL的vector容器,中提供了swap的交换方法,但是只能交换两个vector,或者交换一段内容.
vectory <string> sentence;
sentence.push_back( "hello ");
sentence.push_back( "how ");
sentence.push_back( "are ");
sentence.push_back( "you ");
sentence.push_back( "csdn ");
我想实现:
sentence[0]= "csdn ", sentence[4]= "hello "
不如道如何实现!
[解决办法]
swap是可以交换vector的变量
代码如下
int main(int argc, char* argv[])
{
std::vector <string> sentence;
sentence.push_back( "hello ");
sentence.push_back( "how ");
sentence.push_back( "are ");
sentence.push_back( "you ");
sentence.push_back( "csdn ");
swap( sentence[0] ,sentence[4] );
return 0;
}
[解决办法]
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
int main(int argc, char* argv[])
{
vector <string> vTest;
vTest.push_back( "a ");
vTest.push_back( "b ");
vTest.push_back( "c ");
vTest.push_back( "d ");
swap(vTest[0], vTest[3]);
vector <string> ::iterator pos;
for (pos = vTest.begin(); pos != vTest.end(); pos++)
{
cout < < *pos < < endl;
}
return 0;
}