小编sha*_*ing的帖子

我可以用C++创建一个新的运算符吗?

MATLAB数组支持矩阵运算和元素运算.例如,M*NM.*N.这是区分两种不同操作的非常直观的方式.如果我想在C++中实现类似的操作,我该怎么做?

我也可以创建一个新的运营商.*吗?如果是的话,有人可以给我一些指导吗?

c++

34
推荐指数
6
解决办法
3万
查看次数

为什么valarray这么慢?

请原谅我对valarray的问题.我正在尝试使用它,因为它在操作矢量和矩阵时非常类似于matlab.我首先做了一些性能检查,发现valarray无法实现stroustrup在c ++编程语言中声明的性能.

测试程序实际上做了双倍的5M乘法.我认为c = a*b至少可以与for循环双重型元素乘法相媲美,但我完全错了.试过几台电脑和vc6.0和vs2008.

顺便说一句,我使用以下代码在matlab上测试:

len = 5*1024*1024;
a = rand(len, 1);
b = rand(len, 1);
c = zeros(len, 1);
tic;
c = a.*b;
toc;
Run Code Online (Sandbox Code Playgroud)

结果是46ms.这个时间精度不高,仅作为参考.

代码是:

#include <iostream>
#include <valarray>
#include <iostream>
#include "windows.h"

using namespace std;
SYSTEMTIME stime;
LARGE_INTEGER sys_freq;

double gettime_hp();

int main()
{
    enum { N = 5*1024*1024 };
    valarray<double> a(N), b(N), c(N);
    QueryPerformanceFrequency(&sys_freq);
    int i, j;
    for (j=0 ; j<8 ; ++j)
    {
        for (i=0 ; i<N ; ++i)
        {
            a[i] = rand();
            b[i] …
Run Code Online (Sandbox Code Playgroud)

c++ valarray

20
推荐指数
3
解决办法
1万
查看次数

cin stream无限循环,为什么?

我从c ++编程语言中复制了这个简单的程序,但是我无法按照需要运行它.我错过了什么吗?基本上,程序将在我点击返回后输出"输入结束",然后从cin重复输入.它永远不能进入下一个声明.我试图使用向量(下面评论两个语句),相同.试过Vc6和vs2008.

    #include <iostream>
#include <map>
#include <algorithm>
#include <string>
#include <iterator>
#include <vector>
using namespace std;

map<string, int> histogram;
void record(const string &s)
{
    histogram[s]++; //this is pretty strange, however it does work!
    cout<<"recorded:"<<s<<" occurance="<<histogram[s]<<"\n";
}

void print(const pair<const string,int> &r)
{
    cout<<r.first<<' '<<r.second<<'\n';
}

int main()
{
    istream_iterator<string> ii(cin);
    istream_iterator<string> eos;
    cout<<"input end\n";

    for_each(ii,eos,record); //this statement cannot get out why? It repeats the keyboard input
    //vector<string> b(ii,eos);
    //for_each(b.begin(),b.end(),record);
    for_each(histogram.begin(),histogram.end(),print); //program never comes here why?
}
Run Code Online (Sandbox Code Playgroud)

运行结果:

ABC

输入端 …

c++

5
推荐指数
1
解决办法
380
查看次数

标签 统计

c++ ×3

valarray ×1