我有一個Vector接受地圖對象作爲元素,其中Student是一個包含學生的組的名稱和ID的類。 將地圖存儲到矢量中之後,現在我想根據索引或基於地圖本身刪除地圖。這意味着如果我想要刪除矢量中的map2,那麼它應該刪除map2或第二個元素。我已經使用擦除,迭代器等用於刪除元素,但是當我使用迭代我收到以下錯誤:從基於索引不工作的向量中刪除元素不工作C++ Visual Studio
Error 3 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const Student' (or there is no acceptable conversion)
當我使用:
coll.erase(coll.begin()+2);
我可以能夠只刪除結束/最後的向量的元素不管指數我提供,而不是圖是在位置2
我的計劃:
#include <map>
#include <iostream>
#include "student.h"
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
static int i=0,j=1;
vector<map<int,Student>> coll;
typedef std::map<int,Student> Mymap;
Mymap c1;
map<int, Student> mine(int key,Student value)
{
c1.insert(Mymap::value_type(key,value));
return c1;
}
void print(Mymap a)
{
Mymap m2;
coll.push_back(a);
m2 = coll[i];
i++;
Student s1 = m2.at(j);
j++;
}
int main()
{
typedef map<int, Student> map1;
Student s[5];
Student s1;
map1 m1;
s[0].setName("SAI");
s[1].setName("RAVI");
s[2].setName("RAJU");
s[3].setName("HemaChandra");
s[4].setName("Tushar");
s[0].setId(10);
s[1].setId(20);
s[2].setId(30);
s[3].setId(40);
s[4].setId(50);
m1 = mine(1,s[0]);
s1 = m1.at(1);
print(m1);
m1 = mine(2,s[1]);
s1 = m1.at(2);
print(m1);
m1 = mine(3,s[2]);
s1 = m1.at(3);
print(m1);
m1 = mine(4,s[3]);
s1 = m1.at(4);
print(m1);
m1 = mine(5,s[4]);
s1 = m1.at(5);
print(m1);
cout<<endl<<endl;
cout<<"Before Deleting"<<endl;
for(int i=0,j=1;i<coll.size();i++,j++)
{
Mymap m3 = coll[i];
Student st = m3.at(j);
std::cout <<" "<< st.getName()<<std::endl;
}
cout<<"\nAfter Deleting"<<endl;
coll.erase(coll.begin()+2);
// coll.erase(std::remove(coll.begin(), coll.end(), m1), coll.end()); -------Error when using this statement
for(int i=0,j=1;i<coll.size();i++,j++)
{
Mymap m3 = coll[i];
Student st = m3.at(j);
std::cout <<" "<< st.getName()<<std::endl;
}
return 0;
}
Student.cpp
#include "student.h"
void Student :: setName(string nam)
{
name = nam;
}
void Student :: setId(int i)
{
id = i;
}
string Student :: getName()
{
return name;
}
int Student :: getId()
{
return id;
}
Student.h:
#include<iostream>
using namespace std;
class Student
{
public:
string name;
int id;
void setName(string nam);
void setId(int i);
string getName();
int getId();
};
所有我需要的是,我想在距離向量的特定位置刪除的地圖。也就是說,如果我想要刪除位置2上的地圖,那麼地圖應該被刪除,並且如果我想刪除位置「n」中的地圖,那麼第n張地圖應該被刪除。請幫我解決這個問題。我無法找到我所犯的錯誤。
我得到以下編譯器錯誤,當我使用擦除()函數:
顯示爲'Student'代碼。看起來你缺少一個比較運算符。 – NathanOliver
謝謝。我添加了程序 –
謝謝你的幫助。但我沒有得到你。我應該在哪裏使用std :: advance在程序中? –