use*_*615 1 c++ string integer cout multiplication
我什么时候必须这样做
string s = ".";
Run Code Online (Sandbox Code Playgroud)
如果我做
cout << s * 2;
Run Code Online (Sandbox Code Playgroud)
它会是一样的吗?
cout << "..";
Run Code Online (Sandbox Code Playgroud)
?
JRG*_*JRG 21
std :: string有一个表单的构造函数
std::string(size_type count, char c);
Run Code Online (Sandbox Code Playgroud)
这将重复这个角色.例如
#include <iostream>
int main() {
std::string stuff(2, '.');
std::cout << stuff << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
将输出
..
Run Code Online (Sandbox Code Playgroud)
小智 10
我使用运算符重载来模拟 C++ 中的这种行为。
#include <iostream>
#include <string>
using namespace std;
/* Overloading * operator */
string operator * (string a, unsigned int b) {
string output = "";
while (b--) {
output += a;
}
return output;
}
int main() {
string str = "abc";
cout << (str * 2);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:abcabc
不,std::string没有operator *.您可以将(char,string)添加到其他字符串.请看http://en.cppreference.com/w/cpp/string/basic_string
如果你想要这种行为(没有建议)你可以使用这样的东西
#include <iostream>
#include <string>
template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(const std::basic_string<Char, Traits, Allocator> s, size_t n)
{
std::basic_string<Char, Traits, Allocator> tmp = s;
for (size_t i = 0; i < n; ++i)
{
tmp += s;
}
return tmp;
}
template<typename Char, typename Traits, typename Allocator>
std::basic_string<Char, Traits, Allocator> operator *
(size_t n, const std::basic_string<Char, Traits, Allocator>& s)
{
return s * n;
}
int main()
{
std::string s = "a";
std::cout << s * 5 << std::endl;
std::cout << 5 * s << std::endl;
std::wstring ws = L"a";
std::wcout << ws * 5 << std::endl;
std::wcout << 5 * ws << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
http://liveworkspace.org/code/52f7877b88cd0fba4622fab885907313
没有预定义的*运算符将字符串乘以a int,但您可以定义自己的:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
string operator*(const string& s, unsigned int n) {
stringstream out;
while (n--)
out << s;
return out.str();
}
string operator*(unsigned int n, const string& s) { return s * n; }
int main(int, char **) {
string s = ".";
cout << s * 3 << endl;
cout << 3 * s << endl;
}
Run Code Online (Sandbox Code Playgroud)