C++ STL vector 在迴圈中插入 iterator
C++ STL vector 在迴圈中插入 iterator
插在後面
#include <iostream>
#include <vector>
using namespace std;
void PrintVector1(vector<int> printVector);
bool NeedInsert(vector<int>* pVector, vector<int>::iterator it);
bool NeedInsert2(vector<int>* pVector, vector<int>::iterator it);
int ItToIndex(vector<int>* pVector, vector<int>::iterator it);
void Test01();
void Test02();
int g_p = 115;
int main()
{
Test01();
Test02();
system("pause");
return 0;
}
void Test02()
{
vector<int> myVector;
for (int i = 0; i < 5; i++)
myVector.push_back(i * 10);
cout << "----1" << endl;
PrintVector1(myVector);
cout << "----2" << endl;
int nIndex = 0;
vector<int>::iterator it;
vector<int>::iterator it2;
for (it = myVector.begin(); it != myVector.end(); )
{
if (NeedInsert2(&myVector, it))
{
it2 = it + 1;
if (it2 == myVector.end())
{
myVector.push_back(g_p);
g_p++;
it = myVector.end() - 1;
nIndex++;
cout << nIndex << endl;
}
else
{
it = myVector.insert(it2, g_p);
g_p++;
nIndex++;
cout << nIndex << endl;
}
}
else
{
it++;
nIndex++;
cout << nIndex << endl;
}
}
cout << "----3" << endl;
PrintVector1(myVector);
}
void Test01()
{
vector<int> myVector;
for (int i = 0; i < 5; i++)
myVector.push_back(i * 10);
cout << "----1" << endl;
PrintVector1(myVector);
cout << "----2" << endl;
int nIndex = 0;
vector<int>::iterator it;
vector<int>::iterator it2;
for (it = myVector.begin(); it != myVector.end(); )
{
if (NeedInsert(&myVector, it))
{
it2 = it + 1;
if (it2 == myVector.end())
{
myVector.push_back(g_p);
g_p++;
it = myVector.end() - 1;
nIndex++;
cout << nIndex << endl;
}
else
{
it = myVector.insert(it2, g_p);
g_p++;
nIndex++;
cout << nIndex << endl;
}
}
else
{
it++;
nIndex++;
cout << nIndex << endl;
}
}
cout << "----3" << endl;
PrintVector1(myVector);
}
int ItToIndex(vector<int>* pVector, vector<int>::iterator it)
{
return distance(pVector->begin(), it);
}
bool NeedInsert2(vector<int>* pVector, vector<int>::iterator it)
{
int nIndex = ItToIndex(pVector, it);
if (nIndex == 0)
{
return true;
}
else if (nIndex == 1)
{
return true;
}
else if (nIndex == 6)
{
return true;
}
return false;
}
bool NeedInsert(vector<int>* pVector, vector<int>::iterator it)
{
int nValue = *it;
if (nValue == 0)
{
return true;
}
else if (nValue == 115)
{
return true;
}
return false;
}
//印出方法1
void PrintVector1(vector<int> printVector)
{
vector<int>::iterator it;
for (it = printVector.begin(); it != printVector.end(); it++)
cout << *it << endl;
}
留言
張貼留言