std::list<std::string> lWords; //filled with strings!
for (int i = 0; i < lWords.size(); i++){
std::list<std::string>::iterator it = lWords.begin();
std::advance(it, i);
now I want a new string to be the iterator (these 3 versions won't work)
std::string * str = NULL;
str = new std::string((it)->c_str()); //version 1
*str = (it)->c_str(); //version 2
str = *it; //version 3
cout << str << endl;
}
str should be the string *it but that doesn't work, need help!
In modern c++ we (should) prefer to refer to data by value or reference. Ideally not by pointer unless necessary as an implementation detail.
I think what you want to do is something like this:
#include <list>
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::list<std::string> strings {
"the",
"cat",
"sat",
"on",
"the",
"mat"
};
auto current = strings.begin();
auto last = strings.end();
while (current != last)
{
const std::string& ref = *current; // take a reference
std::string copy = *current; // take a copy
copy += " - modified"; // modify the copy
// prove that modifying the copy does not change the string
// in the list
std::cout << std::quoted(ref) << " - " << std::quoted(copy) << std::endl;
// move the iterator to the next in the list
current = std::next(current, 1);
// or simply ++current;
}
return 0;
}
expected output:
"the" - "the - modified"
"cat" - "cat - modified"
"sat" - "sat - modified"
"on" - "on - modified"
"the" - "the - modified"
"mat" - "mat - modified"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.