Ant*_* Vo 5 c++ iterator intersection list
我正在尝试用一些Java背景学习C++,我正在尝试编写返回两个列表交集的代码.我相信我在概念上有正确的想法,但由于没有任何编译,我的语法有问题.
这是我提出的代码:
#include <iostream>
using namespace std;
#include <list>
template <typename Object>
list<Object> intersection( const list<Object> & L1, const list<Object> & L2){
std::list<Object> result;
int pos1 = 0;
int pos2 = 0;
while (pos1 < L1.size() && pos2 < L2.size()) {
if (L1[pos1] > L1[pos2]) {
pos1++;
} else if (L2[pos2] > L1[pos1]) {
pos2++;
} else {
result.push_back(L2[pos2]);
pos1++;
pos2++;
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
我认为我需要的东西:一个迭代器(我确定我访问列表的方式不正确)
将pos1和pos2更改为迭代器:
list<Object> intersection( const list<Object> & L1, const list<Object> & L2){
std::list<Object> result;
std::list<Object>::iterator pos1 = L1.begin(), pos2 = L2.begin();
while (pos1 != L1.end() && pos2 != L2.end()) {
if (*pos1 > *pos2) { //works only if pos1 != L1.end() and pos2 != L2.end()
pos1++;
...
Run Code Online (Sandbox Code Playgroud)
pos1 = L1.begin()指向pos1的第一个元素L1。
++pos1 将迭代器向前移动到下一个元素
*pos1 从中获取元素 pos1
pos1 != L1.end()检查是否pos1到达列表末尾。您不能从pos1when中获取元素pos1 == L1.end()。