请参见此代码。我需要使用迭代器更改2D字符串向量中特定元素的值。我可以使用带有索引的for循环来做这件事。但这里我需要的是直接使用迭代器来引用元素。像(*ite)[0] = "new name"这样的东西有什么想法吗?为了您的方便,我在这里添加了完整的工作代码
#include <iostream>
#include <vector>
#include <string>
#include <sstream>
using namespace std;
string convertInt(int number)
{
stringstream ss;
ss << number;
return ss.str();
}
int main()
{
vector<vector<string>> studentList;
for(int i=0; i<10; i++){
vector<string> student;
student.push_back("name-"+convertInt(i));
student.push_back(convertInt(i+10));
studentList.push_back(student);
}
vector<string> temp;
for(vector<vector<string>>::iterator ite = studentList.begin(); ite != studentList.end(); ++ite){
temp = *ite;
if(temp[0].compare("name-5")==0){
cout << "Changeing the name of student 5" << endl;
// I need to change the studentList[5][0] (original value not the one in temp vector) at here using iterator ite
}
}
return 0;
}发布于 2013-02-05 14:17:03
因为temp = *ite会复制向量(学生),如果你在temp上修改,它不会在实数studentList上修改,这就是为什么你需要(*ite)[0] = "new name"来改变实数元素的值。
使用for循环有点“丑陋”,使用std::find_if而不是for循环:
bool IsFindFifthName(const std::vector<std::string>& student)
{
return student[0] == "name-5";
}
std::vector<std::vector<std::string>>::iterator iter
= std::find_if(studentList.begin(), studentList.end(), IsFindFifthName);
if (iter != studentList.end() )
{
(*iter)[0] = " new name";
}或者在C++11可用的情况下使用Lambda:
std::vector<std::vector<std::string>>::iterator iter
= std::find_if(studentList.begin(), studentList.end(),
[](std::vector<std::string>& student){ return student[0] == "name-5"; });
if (iter != studentList.end() )
{
(*iter)[0] = " new name";
}发布于 2013-02-05 14:53:55
在这种情况下使用STL算法转换可以是一个很好的选择。该算法在内部使用迭代器。一个示例:
typedef std::vector<std::string> VectorOfString;
void DisplayStudent(const std::vector<VectorOfString>& StudentList)
{
std::for_each(StudentList.cbegin(), StudentList.cend(),
[](const VectorOfString& vectorElement)
{
std::for_each(vectorElement.cbegin(), vectorElement.cend(),
[](const std::string& value)
{
std::cout << value << endl;
});
});
}
std::vector<VectorOfString> StudentList;
std::string data1 = "One";
std::string data2 = "Two";
VectorOfString data(2);
data.push_back(data1);
data.push_back(data2);
StudentList.push_back(data);
DisplayStudent(StudentList);
std::for_each(std::begin(StudentList), std::end(StudentList),
[](VectorOfString& vectorElement)
{
std::transform(std::begin(vectorElement), std::end(vectorElement), std::begin(vectorElement),
[](std::string& value)-> std::string
{
if(value.compare("One") == 0)
return "OneOne";
else
return value;
});
});
DisplayStudent(StudentList);https://stackoverflow.com/questions/14701275
复制相似问题