创建第 3 个向量,同时循环通过其他 2 个向量
Create 3rd vector while looping through 2 others
我完全是 C++ 的新手,我需要用向量解决一个问题。我需要的是合并两个现有向量并创建第三个向量。虽然我看到了几个答案,但这里的区别是我需要向量 #3 (values3) 来包含不是所有的值,而只包含向量 #1 (values1) 和 #2 (values2) 中的值。因此,如果整数 2 在向量 1 中但不在向量 2 中,则此数字不适合我。我应该使用下面提供的功能。注释行是我不知道要写什么的。其他行正在工作。
void CommonValues(vector<MainClass> & values1, vector<MainClass> & values2, vector<MainClass> & values3)
{
MainClass Class;
string pav;
int kiek;
vector<MainClass>::iterator iter3; // ?
for (vector<MainClass>::iterator iter1 = values1.begin(); iter1 != values1.end(); iter1++)
{
for (vector<MainClass>::iterator iter2 = values2.begin(); iter2 != values2.end(); iter2++)
{
if (iter1 == iter2)
{
pav = iter2->TakePav();
iter3->TakePav(pav); // ?
kiek = iter1->TakeKiek() + iter2->TakeKiek();
iter3->TakeKie(kiek); // ?
iter3++; // ?
}
}
}
}
您可以对值 1 和值 2 进行排序,然后使用 std::intersection:http://en.cppreference.com/w/cpp/algorithm/set_intersection
您的代码目前无法运行,除其他问题外,您正在比较向量 1 的迭代器和向量 2 的迭代器,这没有任何意义。如果你想通过循环来完成,你应该遍历一个向量并检查值,例如 *iter1,是否在第二个向量中。
我完全是 C++ 的新手,我需要用向量解决一个问题。我需要的是合并两个现有向量并创建第三个向量。虽然我看到了几个答案,但这里的区别是我需要向量 #3 (values3) 来包含不是所有的值,而只包含向量 #1 (values1) 和 #2 (values2) 中的值。因此,如果整数 2 在向量 1 中但不在向量 2 中,则此数字不适合我。我应该使用下面提供的功能。注释行是我不知道要写什么的。其他行正在工作。
void CommonValues(vector<MainClass> & values1, vector<MainClass> & values2, vector<MainClass> & values3)
{
MainClass Class;
string pav;
int kiek;
vector<MainClass>::iterator iter3; // ?
for (vector<MainClass>::iterator iter1 = values1.begin(); iter1 != values1.end(); iter1++)
{
for (vector<MainClass>::iterator iter2 = values2.begin(); iter2 != values2.end(); iter2++)
{
if (iter1 == iter2)
{
pav = iter2->TakePav();
iter3->TakePav(pav); // ?
kiek = iter1->TakeKiek() + iter2->TakeKiek();
iter3->TakeKie(kiek); // ?
iter3++; // ?
}
}
}
}
您可以对值 1 和值 2 进行排序,然后使用 std::intersection:http://en.cppreference.com/w/cpp/algorithm/set_intersection
您的代码目前无法运行,除其他问题外,您正在比较向量 1 的迭代器和向量 2 的迭代器,这没有任何意义。如果你想通过循环来完成,你应该遍历一个向量并检查值,例如 *iter1,是否在第二个向量中。