Click here to Skip to main content
15,891,248 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi I need help to catch a specific second elemnt of a 2d vector and replace it with a new string.

C++
vector<pair<int,string>> 2dvector;

I have tried by iterator but iterator is a copy of vector and not the vector itself.

What I have tried:

C#
for (vector<pair<int,string>>::iterator it = 2dvector.begin() ; it != 2dvector.end(); ++it)
{
 if (it->second.find("OldString") != std::string::npos)
 {
	it->second.insert("NEWSTRING");
 }

}
Posted
Updated 23-Dec-16 3:08am
v2

In order to replace a string, I would rather use
C++
for ( vector< pair< int, string > >::iterator it = v.begin(); it != v.end(); ++it)
{
  if ( it->second == "OldString")
    it->second = "NEWSTRING";
}

or, with C++11
C++
for ( auto & x : v)
{
  if ( x.second == "OldString")
    x.second = "NEWSTRING";
}
 
Share this answer
 
You can work without iterator ("oldschool-like" if it is easier for you) like this:

C#
vector<pair<int, string>> myVector(10);
myVector[0] = { 1, "test1" };
myVector[1] = { 2, "test2" };
myVector[2] = { 3, "test3" };

int nSize = myVector.size();

for (int i = 0; i < nSize; i++)
{
	if (myVector[i].second == "test2")
		myVector[i].second = "test22";
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900