Efficient way to get a reversed copy of std::string
My question is which approach I should prefer according to efficiency
The one which should be preferred according to efficiency is the one that has been measured to be more efficient. Both have the same asymptotic complexity.
But, I won't bother to measure the difference unless it happens to be a bottleneck. I prefer 2, but it's subjective.
String won't reverse using reverse_copy
The string
you are trying to copy into is too short (zero length). You have to make it long enough to accept the copied data:
std::string A = "abc";
std::string B;
B.resize(A.size()); // make B big enough
std::reverse_copy(A.begin(), A.end(), B.begin());
std::cout << B << '\n';
Currently you are writing past the end of B
causing undefined behavior.
Another way to do this is to use a special iterator called std::back_insert_iterator
, which pushes characters to the back of the target string:
std::string A = "abc";
std::string B;
std::reverse_copy(A.begin(), A.end(), std::back_inserter(B));
The std::back_inserter()
function returns a std::back_insert_iterator
for the string you provide as a parameter (or any container that implements push_back()
, such as std::string::push_back()
).
Note: std::reverse_copy invoked with standard std::string
iterators (as in this example) will simply reverse the code units of a string and not necessarily the characters (depending on the encoding). For example a UTF-8
encoded string that contains multibyte characters would not be reversed correctly by this function as the multibyte sequences would also be reversed making them invalid.
C++ reversing a string
Changes made to the piece of code in question, it works.
for (unsigned int i = size; size >= 0; size--) {
revStr[j] = str[size];
j++;
}
How does reversing a std::string in C++ works with this constructor?
In the code:
std::string original;
std::string reversed(original.rbegin(), original.rend());
The constructor that is called is:
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
Constructs the string with the contents of the range
[first, last)
.
Therefore, the iterator range [original.rbegin(), original.rend())
will be used. rbegin()
and rend()
return reversed iterators. This means that the range will start from the last character of the original string and end at the first character (rend()
points to the previous character to that, which will not be accessed by the constructor since that side of the interval is open).
Output whole sentence when reversing words in string c++
So here is code that can output the sentence from the input file, with each word being reversed and all these words then being outputted in one sentence in the order they were in the sentence. There is still some problems to it, like if there is a non-alphabetic character in the word, at the front or somewhere before the end, that character will be pushed to the back of the word, so this needs to be improved on. Feel free to nicely add constructively criticism if have any. However, think this still provides for the original question. Thank you all for the help.
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
void reverse(string input);
int main(){
ifstream inData;
ofstream outData;
string input;
inData.open("input.txt");
outData.open("output.txt");
while(getline(inData, input)){ //get sentence from input line
reverse(input); //Reverse the sentence
cout << endl; //end line for next sentence
}
inData.close();
outData.close();
return 0;
}
void reverse(string input){
string nonAlpha = "";
bool end = false;
bool nonLetter = true;
while(end != true){
int idx = input.find(" "); //Finds index of blank space
int lastIdx = input.size(); //Finds the last index
if(idx <= 0){ //If it is the last index, then that becomes idx
idx = lastIdx;
end = true;
}
string word = input.substr(0, idx); //Word usually starts from index 0, until the blank space
string x;
for (int i = idx-1; i >= 0; i--){ //Then outputs each letter according to the index of the word
// but starts from last index and decrements thereby reversing the word
if((isalpha(word.at(i))==false)){ //If that index is not a letter then it is stored and will be outputted after word
nonAlpha.push_back(word[i]); //However this can be a problem for non-letter if not at end of word
nonLetter = true;
}
else{
x= word.at(i);
cout << x; //Prints the letter
}
}
if(nonLetter == true){
cout << nonAlpha; //Prints the non-letter
nonAlpha.erase(); //Erases whatever is inside for future non-letters
nonLetter = false; //Makes it false and will be used agaian when there is another non-letter
}
cout << " "; //Space between words
input.erase(0,idx+1); //Erases word when finished reversing and outputting it so can start next word
}
}
what am i doing wrong?reverse string c++
The first you copy when reversing the string is in fact the null terminator so when you are printing it to console it will not show up since the null terminator is the first in the array so you want to do this instead
int size = 12;
char a[12], reverse[12];
strcpy(a, "dlow olleh ");
for (int i = 0; i < strlen(a); i++) {
reverse[i] = a[strlen(a) - (i+1)];
}
reverse[strlen(a)] = '\0';
cout << reverse;
Related Topics
Does Std::Vector *Have* to Move Objects When Growing Capacity? Or, Can Allocators "Reallocate"
What Happens If You Increment an Iterator That Is Equal to the End Iterator of an Stl Container
Why Is Sizeof(Std::String) Only Eight Bytes
How to Identify Platform/Compiler from Preprocessor MACros
How to Get the Number of Characters in a Std::String
How to Catch Python Stdout in C++ Code
Does Moving a Vector Invalidate Iterators
Does a C++11 Range-Based for Loop Condition Get Evaluated Every Cycle
Std::Optional Specialization for Reference Types
Warning: Format Not a String Literal and No Format Arguments
Why Is Memset() Incorrectly Initializing Int
Is Std::String Ref-Counted in Gcc 4.X/C++11
Access Array Beyond the Limit in C and C++
What Does "#Pragma Comment" Mean
How to Get the Class Name from a C++ Object
Setupdigetdeviceproperty Usage Example
What's Up with the Thousands of Warnings in Standard Headers in Msvc -Wall